Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

Q1629 How can I prevent more than four checkboxes being clicked?

irt.org | Knowledge Base | JavaScript | Form | Q1629 [ previous next ]

Q1629 How can I prevent more than four checkboxes being clicked?

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;
}
//--></script>

</head>

<body onLoad="getChecked()">

<form name="myForm">
<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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.