Toggle All Check Boxes using prototype javascript library.
I’ve set up a Demo Page showing this javascript in action.
// updated per visitor comment below
function toggleChkBoxMethod2(formName){ // toggle Check Boxes using Prototype Library var form=$(formName); var i=form.getElements('checkbox'); i.each(function(item) { item.checked = !item.checked; } ); // set our toggle box $('togglechkbox').checked = !$('togglechkbox').checked; }Example Form HTML using this function:
<form name="testform2" > <p > Toggle All Checkboxes: <input type="checkbox" id="togglechkbox" onClick=toggleChkBoxMethod2(testform2); /> </p> <input id="EXCESS_AMT0" name="isNotUsed" type="checkbox" /> <input id="EXCESS_AMT1" name="isNotUsed" type="checkbox" /> <input id="EXCESS_AMT2" name="isNotUsed" type="checkbox" /> </form>
to call use no quotes around the form name:
onClick=toggleCheckBoxes(formName);
Another example using some prototype shorthand to enable and disable a single checkbox:
for this input checkbox element:
< input id="EXCESS_AMT0" name="isNotUsed" type="checkbox" >
which has the id=”EXCESS_AMT0″
we can manipulate this input field like this:
// Enable checkbox
Field.enable('EXCESS_AMT0');
// uncheck that box
$('EXCESS_AMT0').checked = false;
// Disable checkbox
Field.disable('EXCESS_AMT0');
// Check that box
$('EXCESS_AMT0').checked = true;
If you find this post helpful, please click an ad below. Thanks!
Short and sweet. Thnx!
I didn’t know Field.disable, thanks :)
Wow, first try thanks!
When using a checkbox to trigger the check/uncheck event, remember to assign it an id and create an exception inside the function within toggleCheckBoxes (like if(item.id == ‘toggle_checkbox’) return; ) or else that checkbox will never change its checked status.
Thank u very very match
thx, I useit sith pleasure
very nice, thanks!
Just a tip, you’re adding some unnecessary conditionals to your anonymous function:
If you have the element already, then you could do this to make things faster.
function(checkBox){
checkBox.checked = !checkBox.checked
}
However, this can be extended. If you have the
idof a checkbox, you can use something that will get the checkbox for you.function(elem_id){$(elem_id).checked = !$(elem_id).checked
}
Update. Checkboxes have a
clickmethod. This makes life even easier:function(checkBox){
checkBox.click();
}
Thank you for the updates and the post. I hope to update this page in the near future with more information about prototype, and to clarify this code.
Hello Tim -
Have updated this blog entry to reflect your suggested change.
Thanks.
Gare