我们要求将复选框的用户选择限制为最大值。例如,我们从数据库中读取不同的汽车模型,并将它们放在表格上,供用户选择最多两个汽车模型进行进一步处理。我们使用以下代码段(仅限示例代码):
<script type="text/javascript">
function KeepCount()
{
var total=0;
for (var i=0; i < document.car_form.model_selection.length; i++)
{
if(document.car_form.model_selection[i].checked) {
total =total + 1;
}
if (total > 2) {
alert('Pick Just One Please')
document.car_form.model_selection[i].checked = false ;
return false;
}
}
}
</script>
<form action="car_model.php" method="post" name="car_form" id="car_form">
<?php
$q10 = "SELECT ..."
$r10 = mysqli_query ($dbc, $q10);
if (mysqli_num_rows($r10) > 0) {
while ($row10 = mysqli_fetch_array($r10, MYSQLI_ASSOC))
{
echo '<p class="normal_text"><input type="checkbox" name="model_selection[]" value="' . $row10['model_id'] . '" onclick="return KeepCount()"; />' . $row10['car_model_name'] . '</p></br>';
}
}
?>
</form>
此代码不起作用,即使用户选择2个以上的型号,也不会发出警告。
答案 0 :(得分:2)
主要问题是因为获取复选框的dom路径错误。这段代码应该可以迭代所有的复选框。
<!doctype html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
function KeepCount() {
var elements = document.getElementsByName("model_selection[]");
var total = 0;
for(var i in elements) {
var element = elements[i];
if(element.checked) total++;
if(total>2) {
alert("pick one please");
element.checked = false;
return false;
}
}
}
</script>
<form action="car_model.php" method="post" name="car_form" id="car_form">
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id1" onclick="return KeepCount()"></p>
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id2" onclick="return KeepCount()"></p>
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id3" onclick="return KeepCount()"></p>
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id4" onclick="return KeepCount()"></p>
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id5" onclick="return KeepCount()"></p>
<p class="normal_text"><input type="checkbox" name="model_selection[]" value="id6" onclick="return KeepCount()"></p>
</form>
</body>
</html>
答案 1 :(得分:0)
试试这个
<script type="text/javascript">
function KeepCount() {
var inputTags = document.getElementsByName('model_selection[]');
var total = 0;
for (var i = 0; i < inputTags.length; i++) {
if (inputTags[i].checked) {
total = total + 1;
}
if (total > 2) {
alert('Pick Just One Please')
inputTags[i].checked = false;
return false;
}
}
}
</script>
上面代码的问题是model_selection而不是数组,所以它抛出错误未定义的“length”属性。