Forum Moderators: open
<SCRIPT TYPE="text/javascript" LANGUAGE=JAVASCRIPT>
<!--
function checkCheckBoxes() {
if (document.frmTest.CHKBOX_1.checked == false &&
document.frmTest.CHKBOX_2.checked == false &&
document.frmTest.CHKBOX_3.checked == false)
{
alert ('You didn\'t choose any of the checkboxes!');
return false;
}
else
{
return true;
}
}
//-->
</SCRIPT>
<form onsubmit="return checkCheckBoxes();" action="">
<input type="checkbox" name="CHKBOX_1" value="1">1</p>
<input type="checkbox" name="CHKBOX_2" value="2">2</p>
<input type="submit" value="Submit!" />
</form>
<form onsubmit="return checkCheckBoxes(['CHKBOX_1', 'CHKBOX_2']);" action="">
<script type="text/javascript">
function checkCheckBoxes(checkboxNames) {
var i, el;
for (i = 0; i < checkboxNames.length; i++) {
el = document.frmTest[checkboxNames[i]];
if (el) {
if (el.checked) {
// found a checked checkbox
return true;
}
}
}
// No checked checkboxes were found
return false;
}
</script>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<script type="text/javascript">
window.onload=function() {
frm = document.getElementById('myform');
if (frm) { frm.onsubmit=function() { return validateFrm(this); }; }
};
//
function validateFrm(form) {
// iterate through form elements, look for checkboxes
var check_count=0;
var msg='';
for (j=0;j<form.elements.length;j++) {
var type = form.elements[j].type;
if (type == 'checkbox') {
msg += form.elements[j].id + ' checked: ' +
form.elements[j].checked + "\n";
if (form.elements[j].checked) { check_count++; }
}
}
// You could return true here if check_count > 0 . . .
// if (check_count==0) { alert('no checks'); return false; }
// else { return true; }
msg = "total checked: " + check_count + "\n" + msg;
alert(msg);
return false;
}
</script>
</head>
<body>
<form action="" id="myform" method="post">
<p><input type="checkbox" name="one" id="one" value="one"> <label for="one">One</label></p>
<p><input type="checkbox" name="two" id="two" value="two"> <label for="two">Two</label></p>
<p><input type="checkbox" name="three" id="three" value="three"> <label for="three">Three</label></p>
<p><input type="checkbox" name="four" id="four" value="four"> <label for="four">Four</label></p>
<p><input type="submit" value="Submit"</p>
</form>
</body>
</html>
window.onload=function() {
var requireds=['one','three'];
frm = document.getElementById('myform');
if (frm) { frm.onsubmit=function() { return validateFrm(this,requireds); }; }
};