我有这个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>
而且,我有placed my code in a fiddle,它正常工作。我真正想要做的是,当没有选中任何复选框时,我希望自动选中 all 复选框。
答案 0 :(得分:3)
尝试以下方法:
$('input[type=checkbox]').change(function(){
if ($('input[type=checkbox]:checked').length == 0) {
$('#city_all').prop('checked', true)
}
})
答案 1 :(得分:0)
$('input[type="checkbox"]').change(function(){
if($('input[type="checkbox"]:checked').length == 0)
$('#city_all').attr('checked', 'checked');
});
答案 2 :(得分:0)
你真正需要的只是一条线?
$('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);
});