Validate that at least one checkbox is checked

Z

Zvonko Bi¹kup

Hi!

I have 5 checkboxes with the same name:
<input type="checkbox" name="check" value="XYZ" />
<input type="checkbox" name="check" value="ZXY" />
<input type="checkbox" name="check" value="MHG" />
<input type="checkbox" name="check" value="IOJ" />
<input type="checkbox" name="check" value="BGT" />

How to check if at least one is checked?

Thanks
Zvonko
 
I

Ivo

I have 5 checkboxes with the same name:
<input type="checkbox" name="check" value="XYZ" />
<input type="checkbox" name="check" value="ZXY" />
<input type="checkbox" name="check" value="MHG" />
<input type="checkbox" name="check" value="IOJ" />
<input type="checkbox" name="check" value="BGT" />

How to check if at least one is checked?

Assuming they are inside a form named "f", try something like:

var els = document.forms.f.elements;
var i = els.length;
var flag = false;
while( i-- ) {
if( els.name==='check' && els.checked ) {
flag = true; break;
}
}
alert( flag ? 'There is a checkbox checked' : 'Try again.' );

hth
ivo
http://4umi.com/web/javascript/
 
L

-Lost

Zvonko Bi¹kup said:
Hi!

I have 5 checkboxes with the same name:
<input type="checkbox" name="check" value="XYZ" />
<input type="checkbox" name="check" value="ZXY" />
<input type="checkbox" name="check" value="MHG" />
<input type="checkbox" name="check" value="IOJ" />
<input type="checkbox" name="check" value="BGT" />

How to check if at least one is checked?

document.forms['form_name'].elements['check'] will give you a nodeList of your checkboxes.
You can then iterate them with a loop checking for the "checked" value to be true. If
none are true, nothing is checked.

-Lost
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,535
Members
45,008
Latest member
obedient dusk

Latest Threads

Top