使用以下 HTML 复选框代码
<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010
我需要对以下 jQuery 进行哪些更改
$(function() {
$('input[type="checkbox"]').bind('click',function() {
$('input[type="checkbox"]').not(this).prop("checked", false);
});
});
以便始终选中其中一个复选框,不允许空白复选框?
最佳答案
看来您不想使用单选按钮。 这是您的更新代码,它可以按预期工作。您需要确保重新单击时不会取消选中复选框。
$(function() {
$('input[type="checkbox"]').bind('click',function() {
if($(this).prop('checked') === false) {
$(this).prop('checked', true);
}
$('input[type="checkbox"]').not(this).prop("checked", false);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<input type="checkbox" class="example" checked />2016
<input type="checkbox" class="example" />2015
<input type="checkbox" class="example" />2014
<input type="checkbox" class="example" />2013
<input type="checkbox" class="example" />2012
<input type="checkbox" class="example" />2011
<input type="checkbox" class="example" />2010
关于javascript - jQuery 总是选中一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39239489/