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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkbox Validation

Status
Not open for further replies.

Mighty

Programmer
Feb 22, 2001
1,682
US
Guys,

I have a page that has several checkboxes - all with the same name. How do I validate that at least one of them has been selected? I have tried looping through all the instance using "myform.country.length" - where country is the name of the checkboxes - but this doesn't work. Mighty :)
 
<form name=frm onsubmit=&quot;return Check4Check()&quot; method=post>
<input type=checkbox name=&quot;check1&quot;><br>
<input type=checkbox name=&quot;check1&quot;><br>
<input type=checkbox name=&quot;check1&quot;><br>
<input type=checkbox name=&quot;check1&quot;><br>
<input type=checkbox name=&quot;check1&quot;><br>
<input type=submit>
</form>
<script>
function Check4Check()
{
var i = document.frm.check1.length;
for (j=0;j<i;j++)
{
alert(document.frm.check1(j).checked)
}
}
</script>
 
I think this js code may help you.

//use is the name of the checkboxes
var noOfEl = document.getElementsByName(&quot;use&quot;)
//loop through the checkboxes checking each one to
//see if it has been checked
for(var i=0;i<noOfEl.length;i++) {
if (noOfEl.checked) {
//do your other stuff here
}
}
 
try this:

<script language=&quot;javascript&quot;>

function checkboxLoop()
{
var sub1 = &quot;&quot;;
var total = &quot;&quot;;
var DM = document.MyF1;
var NrCbs = DM.country.length;

for (ia = parseInt(0); ia < NrCbs; ia++)
{
if (DM.country[ia].checked)
sub1 = sub1 + ' - ' + DM.country[ia].value;
}

if (!sub1 == &quot;&quot;)
{
total = &quot;these checkboxes are checked :&quot; + sub1;
alert(total);
}
else
{
alert(&quot;no checkboxes are selected&quot;);
}
}


</script>

<form name=&quot;MyF1&quot;>
a: <INPUT TYPE=&quot;checkbox&quot; value=&quot;a&quot; name=&quot;country&quot;>
b: <INPUT TYPE=&quot;checkbox&quot; value=&quot;b&quot; name=&quot;country&quot;>
c: <INPUT TYPE=&quot;checkbox&quot; value=&quot;c&quot; name=&quot;country&quot;>
<br>
<input type=&quot;submit&quot; value=&quot;go&quot; name=&quot;submit777&quot; ONCLICK=&quot;checkboxLoop();return false;&quot;>
</form> <!-- My sport: Boomerang throwing !!
This year I will participate at the World Championships in Germany. (!! Many Happy Returns !! -->
 
Thanks for the pointers guys. It made me realise that my code was OK after all. I just had a lower case letter in my if statement instead of an upper case - so it couldn't locate the checkbox!! Mighty :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top