2014-09-28 71 views
1

我試圖限制選定的checboxes每個錶行3,使用JS。每一行都有一個分離複選框和5倍的水平,這可以選擇只有2,如:限制每個表格行的複選框選擇

<tr> 
    <td> 
     <input type="checkbox" name="indicator[]"> 
    </td> 
    <td> 
     <input type="checkbox" name="graduations[]"> 
    </td> 
    <td> 
     <input type="checkbox" name="graduations[]"> 
    </td> 
    <td> 
     <input type="checkbox" name="graduations[]"> 
    </td> 
    <td> 
     <input type="checkbox" name="graduations[]"> 
    </td> 
    <td> 
     <input type="checkbox" name="graduations[]"> 
    </td> 
</tr> 

實際的代碼作爲看到的http://www.javascriptkit.com/script/script2/checkboxlimit.shtml

function checkboxlimit(checkgroup, limit){ 
    var checkgroup=checkgroup 
    var limit=limit 
    for (var i=0; i<checkgroup.length; i++){ 
     checkgroup[i].onclick=function(){ 
     var checkedcount=0 
     for (var i=0; i<checkgroup.length;checkedcount+=(checkgroup[i].checked)? 1 : 0 
      if (checkedcount>limit){ 
       alert("You can only select a maximum of "+limit+" checkboxes") 
      this.checked=false 
      } 
     } 
    } 
} 

我只能限制對整個表。有沒有簡單的方法來做到這一點?

+0

所以,只有兩個應該在畢業的所有複選框被選中? – 2014-09-28 17:49:48

+0

請檢查標題中的拼寫。 – 2014-09-28 17:50:28

回答

1

如果你有機會到jQuery的你可以使用parent().siblings()選中的複選框的#來限制2每排

$(function() { 
    $('input[name=graduations\\[\\]]').click(function(){ 
     if($(this).parent().siblings().children("input[name=graduations\\[\\]]:checkbox:checked").length >= 2) 
      this.checked = false; 
    }); 
}); 

http://jsfiddle.net/p2dLu2mu/