SoFunction
Updated on 2025-02-28

Restrict the maximum number of optional check boxes

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>html-</title>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
//The name prefix of the checkbox element, this example is sample1, sample2, sample3...
var sCtrlPrefix = "sample";
//The number of checkbox elements, there are 18 in this example;
var iMaxCheckbox = 18;
//Set the maximum allowed number of selected items;
var iMaxSelected = 5;

function doCheck(ctrl) {
var iNumChecked = 0;
var thisCtrl;
var i;

//initialization
i = 1;
//Loop until the most checkbox is selected;
while ((i <= iMaxCheckbox) && (iNumChecked <= iMaxSelected)) {

thisCtrl = eval("." + sCtrlPrefix + i);

if ((thisCtrl != ctrl) && ()) {

iNumChecked++;
}

i++;
}

// Check whether the maximum number of choices has been reached;
if (iNumChecked == iMaxSelected) {
// If so, uncheck the element just selected;
= false;
}
}
// -->
</SCRIPT>


<form name="form" method="post">
<table align="center" border="1" cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="CHECKBOX" name="sample1" onClick="doCheck(this)">
A</td>
<td>
<input type="CHECKBOX" name="sample2" onClick="doCheck(this)">
B</td>
<td>
<input type="CHECKBOX" name="sample3" onClick="doCheck(this)">
C</td>
</tr>
<tr>
<td>
<input type="CHECKBOX" name="sample4" onClick="doCheck(this)">
D</td>
<td>
<input type="CHECKBOX" name="sample5" onClick="doCheck(this)">
E</td>
<td>
<input type="CHECKBOX" name="sample6" onClick="doCheck(this)">
F</td>
</tr>
<tr>
<td>
<input type="CHECKBOX" name="sample7" onClick="doCheck(this)">
G</td>
<td>
<input type="CHECKBOX" name="sample8" onClick="doCheck(this)">
H</td>
<td>
<input type="CHECKBOX" name="sample9" onClick="doCheck(this)">
I</td>
</tr>
<tr>
<td>
<input type="CHECKBOX" name="sample10" onClick="doCheck(this)">
J</td>
<td>
<input type="CHECKBOX" name="sample11" onClick="doCheck(this)">
K</td>
<td>
<input type="CHECKBOX" name="sample12" onClick="doCheck(this)">
L</td>
</tr>
<tr>
<td>
<input type="CHECKBOX" name="sample13" onClick="doCheck(this)">
M</td>
<td>
<input type="CHECKBOX" name="sample14" onClick="doCheck(this)">
N</td>
<td>
<input type="CHECKBOX" name="sample15" onClick="doCheck(this)">
O</td>
</tr>
<tr>
<td>
<input type="CHECKBOX" name="sample16" onClick="doCheck(this)">
P</td>
<td>
<input type="CHECKBOX" name="sample17" onClick="doCheck(this)">
Q</td>
<td>
<input type="CHECKBOX" name="sample18" onClick="doCheck(this)">
R</td>
</tr>
</table>
</form>
</body>
</html>

<div style="position: absolute; top: 10; right: 10; width: 148; height: 18;cursor:hand">
<input type="button" name="Button" value="View source code" onClick= ' = "view-source:" + '></div>