如果选中其中一个,则禁用其他相同值复选框。
<input type='checkbox' name='check[]' value = '1'>
<input type='checkbox' name='check[]' value = '2'>
<input type='checkbox' name='check[]' value = '1'>
<input type='checkbox' name='check[]' value = '2'>
答案 0 :(得分:7)
使用change()
事件处理程序并根据checked属性禁用其他元素。您可以使用filter()
方法和attribute equals selector方法获取具有相同值的其他元素。
// cache the elements
var $chk = $("[name='check[]']");
// bind change event handler
$chk.change(function() {
$chk
// remove current element
.not(this)
// filter out element with same value
.filter('[value="' + this.value + '"]')
// update disabled property based on the checked property
.prop('disabled', this.checked);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='checkbox' name='check[]' value='1'>
<input type='checkbox' name='check[]' value='2'>
<input type='checkbox' name='check[]' value='1'>
<input type='checkbox' name='check[]' value='2'>
答案 1 :(得分:3)
如果你想只禁用具有相同值的其他复选框而不是选中复选框,那么这样的东西应该有效:
$("input[name='check[]']").on('click', function() {
var val = $(this).val();
var parent = $(this);
$("input[value='"+val+"']").each(function() {
$(this).not(parent).attr('disabled', parent.is(':checked'));
});
})
答案 2 :(得分:0)
你的HTML:
<input type='checkbox' class="chk" id="chk_id" name='check[]' value = '1'>
<input type='checkbox' class="chk" id="chk_id" name='check[]' value = '2'>
<input type='checkbox' class="chk" id="chk_id" name='check[]' value = '1'>
<input type='checkbox' class="chk" id="chk_id" name='check[]' value = '2'>
你的剧本:
$(document).ready(function(){
$("#chk_id").click(function(){
var current_value = $(this).val();
$("input[type='checkbox']").each(function() {
if($(this).val() == current_value){
$(this).attr("disabled", true);
}
});
});
});