September 7, 2010

Select All Checkboxes With jQuery

There are other ways to do this, but this way is pretty easy and it works nicely. As simple as it is though, I still tend to forget the syntax, so at least I'll know where to look when I forget.




Some
Checkboxes
for testing
script
(Please note that blogger removes my closing forward slashes.)
<form action="" id="formFooBar" method="post">
<input id="select-all-jq" type="checkbox" /> <label for="select-all-jq">Select all with jQuery</label>
<input id="select-all-js" type="checkbox" /> <label for="select-all-js">Select all with JavaScript</label>
<hr />
<input class="foo-list" name="bar[1]" type="checkbox" /> Some
<input class="foo-list" name="bar[2]" type="checkbox" /> Checkboxes
<input class="foo-list" name="bar[3]" type="checkbox" /> for testing
<input class="foo-list" name="bar[4]" type="checkbox" /> script
</form>
Select all using jQuery
    $("#select-all-jq").click(function(){
        if(this.checked) {
            $(".foo-list").attr('checked','checked');
        } else {
            $(".foo-list").removeAttr('checked');
        }
    });
Select all using only JavaScript (no library), the extra length isn't so bad because this is the whole iceberg so to speak, no extra code elsewhere. The problem really is redoing the browser detection 2 times and the declaration of event listener is different IE/W3C for my code here. I either have to rewrite it, abstract away the browser differences, or live with my ad-hoc browser detection, which will probably lead to confusion and pain down the road.
    "use strict";
    function SelectAll(formName, toggler, classNameOfList)
    {
        this.toggler = document.getElementById(toggler);
        this.form = document.getElementById(formName);
        this.classNameOfList = classNameOfList;

        this.toggle = function (e) {

            var i = 0, n = this.form.elements.length, targetChecked = null;

            if(document.all) { // IE check
                targetChecked = e.srcElement.checked;
            } else {
                targetChecked = e.target.checked;
            }

            for (i; i < n; i = i + 1) {
                if (this.form.elements[i].className.indexOf(classNameOfList) !== -1) {
                    this.form.elements[i].checked = targetChecked;
                }
            }
        };
    }

    var selectAllFooList = new SelectAll('formFooBar', 'select-all-js', 'foo-list');
    
    if(document.all) { // IE Check
        selectAllFooList.toggler.attachEvent('onclick', function(e) { selectAllFooList.toggle(e); });
    } else {
        selectAllFooList.toggler.addEventListener('click', selectAllFooList.toggle, false);
    }

No comments: