Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

validation of check boxes 1

Status
Not open for further replies.

drumin

Technical User
Mar 18, 2001
10
GB
In one of our forms we have a page with lots of checkboxes on it. These are all grouped together, into groups with the name C1, C2, etc. At the moment the customer can bypass these and go to the next page. We need to stop this and force them to choose an option (e.g. this could be one C1 or could be two C1's, one C3 and one C4.

So, the validation just needs to check that at least one box has been checked.

Hope someone can help here!
 
document.forms.formname.checkboxname.checked returns true if checked & false if not

use it Victor
 
This small script will check all elements with the name starting with "C". Provided no other elements in your form start with a capital C, this should work fine for you.


function checkForm(form_ref) {
var boxchecked = false
for (var m = 0; m < form_ref.elements.length; m++) {
if (form_ref.elements[m].name.search(/^C/g) >= 0) {
if (form_ref.elements[m].checked == true) {
boxchecked = true
}
}
}
if (boxchecked == false) {
window.alert(&quot;Please check at least one checkbox&quot;)
// Don't Submit
} else {
// Go ahead and submit
}
}


In the above example, I am assuming that form reference is being passed to the function form_ref. If you're using an actual submit button, you can pass form reference to the function like this.

<form name=&quot;formname&quot; action=&quot;somepage&quot; method=&quot;post&quot; onSubmit=&quot;return checkForm(this);&quot;>

Otherwise, replace the word form_ref with document.forms.formname

Hope this helps.

TW
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top