首页 > 开发 > JS > 正文

限制复选框的最大可选数

2024-09-06 12:45:17
字体:
来源:转载
供稿:网友
<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)">
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表