限制复选框的最大可选数

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>html-</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 method="post">
<table cellpadding="5" cellspacing="0">
<tr>
<td>
<input type="CHECKBOX">
A</td>
<td>
<input type="CHECKBOX">
B</td>
<td>
<input type="CHECKBOX">
C</td>
</tr>
<tr>
<td>
<input type="CHECKBOX">
D</td>
<td>
<input type="CHECKBOX">
E</td>
<td>
<input type="CHECKBOX">
F</td>
</tr>
<tr>
<td>
<input type="CHECKBOX">
G</td>
<td>
<input type="CHECKBOX">
H</td>
<td>
<input type="CHECKBOX">
I</td>
</tr>
<tr>
<td>
<input type="CHECKBOX">
J</td>
<td>
<input type="CHECKBOX">
K</td>
<td>
<input type="CHECKBOX">
L</td>
</tr>
<tr>
<td>
<input type="CHECKBOX">
M</td>
<td>
<input type="CHECKBOX">
N</td>
<td>
<input type="CHECKBOX">
O</td>
</tr>
<tr>
<td>
<input type="CHECKBOX">
P</td>
<td>
<input type="CHECKBOX">
Q</td>
<td>
<input type="CHECKBOX">
R</td>
</tr>
</table>
</form>
</body>
</html>

<div>
<input type="button" value="查看源代码" onClick= 'window.location = "view-source:" + window.location.href'></div>

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjjxyx.html