2013-05-04 54 views
0

我有一個複選框的列表,我想限制1複選框只能被選中,我發現了一塊javascript,這是假設要做到這一點,但一直未能成功地對它進行處理下面是我沒有碰運氣的嘗試。限制複選框爲一個html 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> 
+5

這就是他們發明單選按鈕的原因。 – 2013-05-04 00:07:14

回答

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> 

最後使用單選按鈕將太大的意義,你的情況!