Reputation: 3818
I've got a piece of JavaScript that is supposed to check or UN-check ALL my check boxes (named the same) .. works fine when there is more than one check box... doesn't work if only one check box exists. (I realize that the practical difference between clicking 'check All' on a single option screen is identical, and one could argue that the 'check All' shouldn't even appear on a screen with only ONE option - however the client is insistent on consistent screens...so please don't take me down a route I've already argued)
the script:
// check uncheck all check boxes
var checkAll = function( checkname, exby ) {
alert( checkname.length ); // undefined when there is only one check box
for ( i = 0; i < checkname.length; i++ ) {
checkname[i].checked = exby.checked ? true : false;
}
}
NOTE - I added an alert to check the length, and it is undefined when there is only ONE check box, but is accurate any other time????
the HTML that DOESN'T work...
<form method="post" name="createInvoice" >
Check/Uncheck All <input name="chkAll" onclick="checkAll( document.createInvoice.PO, this );" type="checkbox" >
<input name="PO" value="7835" class="chkbox" type="checkbox" >
</form>
the HTML that DOES...
<form method="post" name="createInvoice" >
Check/Uncheck All <input name="chkAll" onclick="checkAll( document.createInvoice.PO, this );" type="checkbox" >
<input name="PO" value="13506" class="chkbox" type="checkbox" >
<input name="PO" value="14046" class="chkbox" type="checkbox" >
</form>
Upvotes: 0
Views: 339
Reputation: 128317
I believe that when you have one checkbox with the name "PO", then document.createInvoice.PO
will evaluate to the single DOM element with that name. When there is more than one, apparently it will give you a list of DOM elements, which has a length
property.
So when there's only one, you aren't getting a length.
You could add logic to handle either case:
var checkAll = function( checkbox, exby ) {
var checkboxes = checkbox.length ? checkbox : [checkbox];
for ( i = 0; i < checkboxes.length; i++ ) {
checkboxes[i].checked = exby.checked;
}
};
Upvotes: 2
Reputation: 123739
It is because thats how it has been implemented.
Name can be used in the document.getElementsByName() method, a form and with the form elements collection. When used with a form or elements collection, it may return a single element or a collection.
var checkAll = function( checkname, exby ) {
if(!checkname.length)
{
checkname.checked = exby.checked ? true : false;
return;
}
alert( checkname.length ); // undefined when there is only one check box
for ( i = 0; i < checkname.length; i++ ) {
checkname[i].checked = exby.checked ? true : false;
}
}
Upvotes: 2
Reputation: 5858
If it is only 1 then it is the element, and not an array.
if (!!checkname.length) {
for ( i = 0; i < checkname.length; i++ ) {
checkname[i].checked = exby.checked ? true : false;
}
} else {
checkname.checked = exby.checked ? true : false;
}
Upvotes: 3