I have a form I'm working on with a series of checkboxes, reg0 through reg11, that I'm trying to validate to make sure at least one was checked. However, there are other checkboxes on the form, so I can't just simply count up all of the checkboxes -- I need to check against this specific set of them. Here's what I've tried: // Check to make sure at least one workshop was selected var checkbox_choices = 0; for (counter = 0; counter < 11; counter++) { if (form.reg[counter].checked) { checkbox_choices = checkbox_choices + 1; } } if (checkbox_choices < 1 ) { alert("Please select at least one workshop." + checkbox_choices); form.reg0.focus(); return (false); } Code (markup): I also tried if (form.reg+counter.checked), and that had the curious effect of not erroring, but not counting checkbox_choices either, so it always throws the alert and returns false.
<form action="" method=""> <fieldset id="set_of_checkboxes"> <input type="checkbox" ... /> <input type="checkbox" ... /> <input type="checkbox" ... /> </fieldset> </form> HTML: var set_of_checkboxes=document.getElementById('set_of_checkboxes'); var array_of_all_checkboxes=set_of_checkboxes.getElementsByTagName('input'); //or you may also use var array_of_all_checkboxes=set_of_checkboxes.childNodes; //now iterate the array using for...in loop Code (JAVASCRIPT):
Here's another option: <SCRIPT LANGUAGE="JavaScript"> var checkbox_selected=""; function CheckIfcheckboxButtons() { if (checkbox_selected=="") alert("\nYou must check one of the checkbox buttons."); else { alert("Form has been filled out correctly."); } } </SCRIPT> <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">YES <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">NO <INPUT TYPE="checkbox" NAME="checkboxbutton" onClick="checkbox_selected='WasSelected'">MAYBE <INPUT TYPE="button" VALUE="Check Form Fields" onClick="CheckIfcheckboxButtons()">