限制复选框的最大可选数

来源:互联网 时间:2016-03-23

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>html-www.51windows.Net</title>
</head>
<body>
<SCRIPT LANGUAGE="JavaScript">
<!--
//checkbox元素的名字前缀,本例为sample1,sample2,sample3...
var sCtrlPrefix = "sample";
//checkbox元素数量,本例有18个;
var iMaxCheckbox = 18;
//设置最大允许选择的数量;
var iMaxSelected = 5;

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

//初始化
i = 1;
//循环直到选中了最多的checkbox;
while ((i <= iMaxCheckbox) && (iNumChecked <= iMaxSelected)) {

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

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

iNumChecked++;
}

i++;
}

// 检查是否达到了最大选择数量;
if (iNumChecked == iMaxSelected) {
// 如果是则uncheck刚选择的元素;
ctrl.checked = 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="查看源代码" onClick= 'window.location = "view-source:" + window.location.href'></div>

相关阅读:
Top