我有3个html复选框(<input type="checkbox" id="chkBillTos" class="chk" />
),它们具有相同的类和不同的ID,我想在它们之间进行切换(即,如果一个选中了其他两个,则未选中)。但是,当我单击一个复选框时,它没有被选中,而在那个时候其他两个可以被选中或取消选中。
$(".chk").click(function() {
$('.chk').attr('checked', 'checked');
//$('.chk').attr('unchecked', 'unchecked');
var id = $(this.id);
id.checked = true;
$(id).attr('checked', 'checked');
if (!$(this).is(':checked')) {
alert($(this));
$(this).is(':checked') = true;
}
}
答案 0 :(得分:0)
正如@Rory McCrossan所述,单选按钮可能会更好地适合您(不需要JS)。
<label><input type="radio" name="a"> 1</label>
<label><input type="radio" name="a"> 2</label>
<label><input type="radio" name="a"> 3</label>
如果您仍要使用复选框,请按以下步骤操作:
$('.check').on('change', function () {
if ($(this).prop('checked')) {
$('.check').prop('checked', false);
$(this).prop('checked', true);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" class="check"> 1</label>
<label><input type="checkbox" class="check"> 2</label>
<label><input type="checkbox" class="check"> 3</label>
我使用$.attr()
而不是使用$.prop()
来获取/设置检查状态。
答案 1 :(得分:0)
这将取消选中除当前复选框以外的所有复选框:
$(".chk").click(function() {
$('.chk').not('#'+this.id).prop('checked', false);
});