Prototype - How to check several checkboxes
Posted by Anders Vindberg
in Lunarmedia Blog
on the 11 May. 2007 (43,113 views).
Prototype is a somewhat complex JavaScript library though thoroughly documented it still misses out on some points. For instance, I have a list of checkboxes for which at least one has to be checked. If none of the checkboxes in the group are checked then the user should receive a message indicating the missing action. At first, the most intuitive solution was to use the form.getValues() method in combination with a find() enumerator. However, that method can only loop through an entire form. So I needed a function that could loop through element groups within a form. As always best illustrated with an example:
<ul id="FF_Microsoft">
<li>
<input name="FF_MicrosoftDislike" id="FF_MicrosoftDislike" value="1" type="checkbox" />
<label for="FF_MicrosoftDislike">I generally dislike Microsoft</label>
</li>
<li>
<input id="FF_MicrosoftNone" type="checkbox" value="1" />
<label for="FF_MicrosoftNone">No, none of the above</label>
</li>
</ul>
With the following Javascript:
function IsChecked(el) {
return $$('#' + el + ' input').find(
function(e) {return e.checked;});
};
And in order to use the function you simply:
if(IsChecked('FF_Microsoft') != null)
{
// Do something
};
The naming used in the example may seem a bit strange (its from my upcoming questionnaire).