PDA

View Full Version : Validate many checkbox-same name ?



satkannanab
07-25-2008, 04:01 AM
Hi.
I have a code with 5 check boxes with same name and different Id's.
I need to validate the check boxes that before submitting at least one of the check box must be checked.
Can u give me a sample code and suggest me a logic, that how i can achieve it.

Thanks in advance.
regards,
satheeshkannan.

jscheuer1
07-25-2008, 06:11 AM
With five checkboxes, all with the same name, as long as you don't have other checkboxes or radio buttons in the form with that name, this will work:


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function oneOfFive(f){
for (var e = f.elements, i = e.length - 1; i > -1; --i)
if(e[i].name && e[i].name == 'bob' && e[i].checked)
return true;
alert('Please Check at Least One box');
return false;
}
</script>
</head>
<body>
<form action="#" onsubmit="return oneOfFive(this);">
<input type="checkbox" name="bob" value="">
<input type="checkbox" name="bob" value="">
<input type="checkbox" name="bob" value="">
<input type="checkbox" name="bob" value="">
<input type="checkbox" name="bob" value="">
<input type="submit" value="Go!">
</form>
</body>
</html>

Pretty much whatever else you want to have is up to you. You can give them each an id (all id's must be unique according to spec, and at least for most purposes involving javascript). You can have other elements in the form. Each box can have a value, label, etc.