10 Dec
JavaScript Check/Uncheck Checkboxes
This tutorial is a really simple one and is only a one liner in prototype (slight more in regular JavaScript). It will check all the checkboxes on a page, and a function to uncheck all checkboxes quite handy really especially if you are dealing with long lists.
Check All
$$('input[type="checkbox"]').invoke('writeAttribute', 'checked', 'checked');
What we are doing here is selecting all the inputs of type checkbox and enumerating over them writing a check attribute to each one.
Uncheck All
$$('input[type="checkbox"]').invoke('removeAttribute', 'checked');
As you can guess this just the opposite way round.
JavaScript
You can do the same basic principle without a framework:
// check all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox') {
inputs[i].checked = true;
}
}
// uncheck all
var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == 'checkbox') {
inputs[i].checked = false
}
}
That’s it there isn’t really much to it, but I thought it was worth sharing.




Reply