lundi 17 août 2015

Javascript: Select all checkboxes by classname

I'm having an issue with the following code which selects all checkboxes in the row based on the 'Select All' button clicked. The problem is I have to click each button twice if some checkboxes are already checked in order to change their state. I'd like to do this with just one click on each button no matter if checkboxes are selected or not. Is there a simple way to do this? Thank you!

jsFiddle

<form name="editview">    
<input type="checkbox" id="edit_1" name="check1" class="edit">
<input type="checkbox" id="edit_2" name="check2" class="edit" disabled="disabled" checked="checked">
<input type="checkbox" id="edit_3" name="check3" class="edit" disabled="disabled">
<input type="checkbox" id="edit_4" name="check4" class="edit">
<input type="button" class="button" value="Select All" onclick="CheckUncheckAllAndExcludeDisabledByClass(this,'edit')" title="Select all: items.">
<input type="checkbox" id="view_5" name="check5" class="view">
<input type="checkbox" id="view_6" name="check6" class="view" disabled="disabled" checked="checked">
<input type="checkbox" id="view_7" name="check7" class="view" disabled="disabled">
<input type="checkbox" id="view_8" name="check8" class="view">
<input type="button" class="button" value="Select All" onclick="CheckUncheckAllAndExcludeDisabledByClass(this,'view')" title="Select all: items.">

checked = true;
function CheckUncheckAllAndExcludeDisabledByClass(theElement,theCheckBoxClass) {
    var checks = document.querySelectorAll('.' + theCheckBoxClass);
    for (var i = 0; i < checks.length; i++) {
        var check = checks[i];
        if (!check.disabled) {
            check.checked = checked;
        }
    }
    checked = !checked;
}




Aucun commentaire:

Enregistrer un commentaire