2014-06-16 57 views
0

我有4個以下的複選框。如果其中兩個選擇使用jQuery 012禁用其他複選框

<input type="checkbox" id="41" name="4[]" value="abc" style="width:10px"></td> 
<input type="checkbox" id="42" name="4[]" value="qwe" style="width:10px"></td> 
<input type="checkbox" id="43" name="4[]" value="xyz" style="width:10px"></td> 
<input type="checkbox" id="44" name="4[]" value="pqr" style="width:10px"></td> 

我需要一種方法來禁用其他複選框,如果我選擇其中兩個。

任何幫助將不勝感激。

+5

id應該是唯一的..! –

+0

好的我已更新 – D3Systems

+1

http://jsfiddle.net/ESH54/ – Satpal

回答

3

您可以使用:

$(":checkbox[name='4[]']").change(function(){ 
    if ($(":checkbox[name='4[]']:checked").length == 2)            
    $(':checkbox:not(:checked)').prop('disabled', true); 
    else              
    $(':checkbox:not(:checked)').prop('disabled', false); 
}); 

Working Demo

0

試試這個。

的Javascript

$('input[type=checkbox]').change(function(){ 
    if($(this).is(':checked')){ 
$('input[type=checkbox]').attr('disabled',true); 
    $(this).attr('disabled',''); 
} 
else{ 
$('input[type=checkbox]').attr('disabled',''); 
} 
}); 

HTML

1 <input type="checkbox" name="finallevelusers[]" value="1"/> 
2 <input type="checkbox" name="finallevelusers[]" value="1"/> 
3 <input type="checkbox" name="finallevelusers[]" value="1"/> 
4 <input type="checkbox" name="finallevelusers[]" value="1"/> 

Demo

1

試試這個

$('input:checkbox').on('change', function(evt) { 
    if($(this).siblings(':checked').length >= 2) { 
     this.checked = false; 
     console.log(this.value) 
    } 
}); 

DEMO

0

Demo Fiddle

$('[type="checkbox"]').change(function(){ 

    if(this.checked && $(':checked').length == 2){ 
     $('[type="checkbox"]').not(':checked').prop('disabled',true); 
    } 
}); 
  • 爲您的元素使用唯一的Id屬性。

  • 如果沒有共同的屬性,使用通用類名稱的通用選擇像$('[type="checkbox"]')

  • $(':checked').length:checked僞讓你找到只檢查輸入。

  • .prop('disabled',true);用於禁用輸入 - 請參閱.prop()

0

首先開始爲每個複選框添加唯一的ID。 然後你可以附加功能來改變事件,例如像:

$("input[type=checkbox]").change(function() { 
... 
}); 

然後簡單地計算:檢查的項目,瞧:

var n = $("input:checked").length; 

休息,你可以做你自己的我想。

相關問題