2014-10-30 35 views
0

我有下面的表格,其中的複選框將比較每行中最多3個項目進行比較。添加數字到複選框的屬性和限制選中的複選框的數量

所以我想要一些jQuery,只允許選擇3個複選框,然後它會動態地添加一個數字到名稱屬性的末尾。

所以如果有2個比較,名稱屬性將是「horse_1」和「horse_2」。

我不知道從哪裏開始!

 <tr> 
      <td><input type="checkbox" value="2560092" name="horse_"></td> 
      <td>1</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" value="2560093" name="horse_"></td> 
      <td>2</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" value="2560094" name="horse_"></td> 
      <td>3</td> 
     </tr> 
     <tr> 
      <td><input type="checkbox" value="2560095" name="horse_"></td> 
      <td>4</td> 
     </tr> 
+0

開始通過聽取'change'事件。 – undefined 2014-10-30 06:37:37

+0

您想要限制用戶可以從可用複選框中選擇任意三個複選框的用戶界面..正確..? – 2014-10-30 06:38:31

+0

當他們點擊時會發生什麼?它沒有得到檢查,或者它是否應該通過取消選擇第一項來循環選擇? – Snellface 2014-10-30 07:15:04

回答

2

可以使用獲得所選元素的個數:

var selected = $('input:checked') 
selected.length 

如果所選元素的個數爲3,您可以禁用所有選中的投入。這裏使用jQuery:not()選擇器來獲取:checked屬性的逆。

if (selected.length == 3) { 
     $("input:not(:checked)").prop('disabled', true); 
    } 

,這樣,如果再沒有選擇3無輸入被禁止,然後添加一個else語句。

else { 
     $("input").prop('disabled', false); 
    } 

然後可以使用一個。每()遍歷每個檢查元件來更新他們的名稱,使用的元素的索引集合中的作爲加1的值來對抗零數索引:

$('input:checked').each(function(index, element) { 
     $(element).attr('name', 'horse_' + (index + 1)); 
    }); 

http://jsfiddle.net/bj8L0ct2/1/