我有一组简单的复选框,可以选中多个选项,但我希望它的行为像一个单选按钮,其中总是有一个选项被选中。
如您在我的代码中所见,复选框将被选中,然后取消选中。请让我知道我做错了什么。谢谢
$('input[type=checkbox]').on('click', function(event) {
event.preventDefault();
if($('input[type=checkbox]:checked').length === 1 && $(this).is(':checked')) {
return false;
// there is only one checked AND the checked one is $this and we want to prevent it from uncheck
} else {
$(this).prop('checked', true);
alert($(this).prop('checked')); // this return true
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked"/>
<input type="checkbox"/>
<input type="checkbox"/>
最佳答案
event.preventDefault()
让你的 .prop
不工作
您还需要在选中复选框时取消选中其他复选框。
$('input[type=checkbox]').on('click', function(event) {
// Remove this line
// event.preventDefault();
if ($('input[type=checkbox]:checked').length === 1) {
if ($(this).is(':checked')) {
return false; // this is checked
}
return false; // and this is the only one check
} else {
// Uncheck others
$('input[type=checkbox]').prop('checked', false);
$(this).prop('checked', true);
alert($(this).prop('checked')); // this return true
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="checkbox" checked="checked" />
<input type="checkbox" />
<input type="checkbox" />
关于jQuery .prop ('checked' , true) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29336296/