Validating Radio Buttons


if (radio.checked) {   return true; } 

When a group of radio buttons is mandatory, it suffices that one of these buttons is checked (well, it is not possible to check more than one button per group anyway, but there is still the possibility that none of the buttons is selected). Using the elements array of the form, the group of radio buttons can be selected as an array. Within this array, at least one radio button with checked equals TRue must be found so that the group is considered to be sufficiently filled out. The following listing implements this check:

Validating a Radio Button Group (mandatory-radio.html)

<script language="JavaScript"   type="text/javascript"> function checkform(f) {   for (var i=0; i<f.elements["colors"].length;     i++) {     var radio = f.elements["colors"][i];     if (radio.checked) {       return true;     }   }   // no checked radio button found   window.alert("No color selected!");   f.elements["colors"][0].focus();   return false; } </script> <form onsubmit="return checkform(this);">   <input type="radio" name="colors" value="R" />  red<br />   <input type="radio" name="colors" value="G" />  green<br />   <input type="radio" name="colors" value="B" />  blue<br />   <input type="submit" value="Submit data" /> </form> 

Note

You may want to consider a less obtrusive way of pointing the user to the error in the form. For instance, you could use DOM or the Image object to display a small error icon next to all fields that have not been correctly filled out. This is, of course, a possibility for all validation phrases in this chapter.





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net