如果未选中任何复选框,请选中第一个复选框

Check the first checkbox, if no checkbox is selected

本文关键字:复选框 第一个 任何 如果      更新时间:2024-01-15

我有这个HTML代码

<input type="checkbox" name="city_pref[]" id="city_all" value="0" checked /><label for="city_all">All</label>
<input type="checkbox" name="city_pref[]" id="city_pref_1" value="Chicago" /><label for="city_pref_1">Chicago</label>
<input type="checkbox" name="city_pref[]" id="city_pref_2" value="Texas" /><label for="city_pref_2">Texas</label>

而且,我把我的代码放在小提琴里,它工作正常。我真正想做的是,当没有选中任何复选框时,我希望自动选中all复选框。

尝试以下操作:

$('input[type=checkbox]').change(function(){
    if ($('input[type=checkbox]:checked').length == 0) {
       $('#city_all').prop('checked', true)
    }   
})

演示

$('input[type="checkbox"]').change(function(){
    if($('input[type="checkbox"]:checked').length == 0)
         $('#city_all').attr('checked', 'checked');
});

您真正需要的只是一行?

$('input[type="checkbox"][name="city_pref[]"]').on('change', function(e){
     this.checked ? $(this).siblings('[name="city_pref[]"]').prop('checked', false) : $("#city_all").prop('checked', true);
});

FIDDLE