Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1646 How can I ensure that four and only four checkboxes being clicked in a form?

You are here: irt.org | FAQ | JavaScript | Form | Q1646 [ previous next ]

Try this:

<html>

<head>

<script language="JavaScript"><!--
var numChecked = 0;
var maxChecked = 4;

function getChecked() {
  var theForm = document.myForm;
  for (i=0; i<theForm.elements.length; i++) {
    if (theForm.elements[i].type == 'checkbox' && theForm.elements[i].checked) numChecked++;
  }
}

function checkCheck(theBox) {
  if (theBox.checked) {
    if (numChecked == maxChecked)
      theBox.checked = false;
    else numChecked++;
  }
  else numChecked--
  return true;
}

function validate(form) {
  if (numChecked == maxChecked)
    return true;
  else {
    alert('You need to check ' + minChecked + ' checkboxes');
    return false;
  }
}
//--></script>

</head>

<body onLoad="getChecked()">

<form name="myForm" onSubmit="return validate()">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
<input type="checkBox" onClick="checkCheck(this)">
</form>

</body>

</html>

©2018 Martin Webb