我有一个复选框列表,我想限制1个复选框只能被选中,我发现一段javascript,假设这样做,但未能成功地将它成功地在下面是我试过的没有运气。
<!DOCTYPE html>
<html>
<head>
<title></title>
<link type="text/css" rel="stylesheet" href="style.css" />
<script type="text/javascript">
function control(j) {
var total=0;
for(var i=0; i < document.form1.ckb.length; i++){
if(document.question.ckb[i].checked){
total =total +1;}
if(total > 1){
alert("Please Select only one")
document.question.ckb[j].checked = false ;
return false;
}
}
} </script>
</head>
<body>
<header>
</header>
<div id='wrapper'>
<section id='description'>
<p>This quiz is compossed by 10 questions, you have to answer at least 7
from 10 to pass the exam.</p>
<h2>Good luck!</h2>
</section>
<div id='questions-number'>
<p>Question <span id='current-question'>1</span> of <span>10</span> </p>
</div>
<section id='questions'>
<p id='question'></p>
<ul>
<li><input type='checkbox' id='checkAnswer0' name = ckb answer0 value=0 onclick=' control(0)'/><label id='answer0'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer1' name = ckb answer0 value=1 onclick=' control(2)'/><label id='answer1'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer2' name = ckb answer0 value=2 onclick=' control(3)'/><label id='answer2'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer3' name = ckb answer0 value=4 onclick=' control(4)'/><label id='answer3'>answer0</label></li>
</ul>
</section>
<div id='next'>
next
</div>
</div>
<script type = "text/javascript" src="js/jquery-1.9.1.js"></script>
<script type = "text/javascript" src= "js/question_script.js"></script>
</body>
</html>
答案 0 :(得分:1)
首先,您的html中没有表单,您的脚本将无法正常工作,因为您使用表单访问复选框,要更正此问题,您可以编辑脚本:
<script type="text/javascript">
function control(j) {
var total=0;
var ckbs = document.getElementsByName('ckb');
for(var i=0; i < ckbs.length; i++){
if(ckbs[i].checked)
{
total =total +1;
}
if(total > 1)
{
alert("Please Select only one");
ckbs[i].checked = false ;
return false;
}
}
}
</script>
此外,您需要修复复选框的名称(您没有使用引号):
<li><input type='checkbox' id='checkAnswer0' name ="ckb" value=0 onclick=' control(0)'/><label id='answer0'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer1' name ="ckb" value=1 onclick=' control(2)'/><label id='answer1'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer2' name ="ckb" value=2 onclick=' control(3)'/><label id='answer2'>answer0</label></li>
<li><input type='checkbox' id='checkAnswer3' name ="ckb" value=4 onclick=' control(4)'/><label id='answer3'>answer0</label></li>
最后使用单选按钮对你的情况很有意义!