The title might be misleading, but the kind of validation I was after is checking whether or not at least one option in a group of elements (check boxes or radio buttons) is checked.
This is useful in cases where you want the user to make a choice on their own instead of accepting a default value, or in cases where you can’t supply a default one. I wanted the validation to take place at client-side, before posting the form, so JavaScript is the only option.
I tried different approaches to this matter, but wound up with using the Prototype JavaScript framework which allowed me to construct an efficient little one-liner:
Replace the elements selector with your own. Just make sure it returns a collection of checkboxes or radio buttons. It will return boolean true if at least one of the elements is checked, otherwise false.
It sucks, it’s nothign if you dont post examples on how to use it!
Hi Leo,
Thanks for your feedback. I assumed the readers have some basic knowledge about the Prototype framework and how to work with element selectors.
You simply replace the “elements” string with your own selector pattern for matching check boxes or radio buttons. The return value of my oneliner will be boolean true/false depending on whether or not at least one of the elements that you have matched upon is checked.
Example selector:
$( "#form input[type=checkbox]” )…The above pattern would select all check boxes that is a child of an element with an id of “form”.
Thanks for this. Alternative way to do it without element selectors is as follows:
option 1
option 2
function is_radio_checked(formId,radioGroup)
{
return Boolean($(formId).getInputs(’radio’,radioGroup).find(function(r){ return r.checked; }));
}
clicky testy
See also: http://xavisys.com/using-prototype-javascript-to-get-the-value-of-a-radio-group/
Apologies - didn’t put code tags around the example above so it stripped out my html tags - will try again:
option 1
option 2
function is_radio_checked(formId,radioGroup)
{
return Boolean($(formId).getInputs('radio',radioGroup).find(function(r){ return r.checked; }));
}
clicky testy
OK - failed second time to get my example HTML to display :) Will explain briefly:
First parameter to the function is the ID attribute of the parent HTML FORM. Second parameter is the NAME of the INPUT TYPE=RADIO group in question.
You need to include the prototype.js library before calling this function!