简体   繁体   中英

Javascript check/uncheck all function. IE doesn't update

function checkUncheckAll(theElement) {
        var theForm = theElement.form, z = 0;
        while (theForm[z].type == 'checkbox' && theForm[z].name != 'checkall') {
                theForm[z].checked = theElement.checked;
                z++;
        }
}

theElement is the checkall checkbox at the bottom of a list of checkboxes. when clicked it calls this function to set all checkboxes in the same form to the value of checkall.

It works across all browsers aside from one glitch in IE. After clicking the checkall box it seems like the checkboxes are updated, but you don't see it. If you click anywhere on the page the checkboxes are then updated to their proper status. This happens for both checking and unchecking.

This is easy without jQuery, which is unnecessary here.

function checkUncheckAll(theElement) {
    var formElements = theElement.form.elements;
    for (var i = 0, len = formElements.length, el; i < len; ++i) {
        el = formElements[i];
        if (el.type == "checkbox" && el != theElement) {
            el.checked = theElement.checked;
        }
    }
}

Update

It turned out the main problem was that the checkUncheckAll() function was being called from a change event handler on a checkbox, which doesn't fire in IE until the checkbox loses focus, so the fix was simply a matter of changing it to use a click event handler instead.

The best way to do this is to use jQuery . It does require including a library, but it's well worth it! jQuery handles cross-browser js/DOM issues, and provides an excellent selector syntax and modification methods.

Additional examples similar to yours are hilighted in this Blog Post:

http://www.iknowkungfoo.com/blog/index.cfm/2008/7/9/Check-All-Checkboxes-with-JQuery

function checkUncheckAll(theElement){
    newvalue = $(theElement).is(':checked');  
    $("INPUT[type='checkbox']", theElement.form).attr('checked', newvalue);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM