我希望能够执行上图中的功能。但是,它将无法正常工作。
$("#customSwitches").click(function() {
var $this = $(this);
if ($this.data('clicked')) {
alert("not element clicked");
$this.data('clicked', false);
$(document).on('click', "#radio1, #radio2, #radio3, #radio4").not(this).prop('checked', false);
});
} else {
alert("element clicked");
$this.data('clicked', true);
}
});
答案 0 :(得分:1)
在组中复选框的每次单击中,您可以检查checked
的{{1}}属性。如果未选中,则可以从组中计算#customSwitches
个复选框的长度,如果大于checked
,则可以阻止默认事件。
单击1
时,可以重置组中的所有复选框。
您可以尝试以下方式:
#customSwitches
$(".vehicle").click(function(e){
if($('#customSwitches').is(':not(:checked)')){
if($('.vehicle:checked').length > 1){
alert('You can not check multiple');
e.preventDefault();
}
}
});
$("#customSwitches").click(function(e){
$(".vehicle").prop('checked', false);
});
答案 1 :(得分:0)
您当前的代码存在语法问题,并使用了嵌套事件处理程序,这不是一个好的设计模式。
从基本意义上讲,您正在尝试根据第一个复选框状态构建动态复选框限制器。为此,只需确定第一个框是否已选中,然后计算已选中区域的数量以查看其是否超出限制。如果是这样,则禁止选中当前框。试试这个:
let $allowMulti = $('#allow_multi').on('change', function() {
if (!this.checked)
$('.region').prop('checked', false); // remove all checks if no multi allowed
});
$('.region').on('change', function() {
let selectedCount = $('.region:checked').length;
if (!$allowMulti.prop('checked') && selectedCount > 1)
$(this).prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<label>
<input type="checkbox" id="allow_multi">
Select multiple regions
</label>
</p>
<label>
<input type="checkbox" class="region" value="1"> 1
</label>
<label>
<input type="checkbox" class="region" value="2"> 2
</label>
<label>
<input type="checkbox" class="region" value="3"> 3
</label>
<label>
<input type="checkbox" class="region" value="4"> 4
</label>