As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center作为指导。
                            
                        
                    
                
                7年前关闭。
            
        

我有很多城市输入复选框。我给第一个复选框起了名字All。如果用户选择该选项,则仅选中所有复选框,而不选中其他城市复选框。

如果用户检查了其他城市,则应自动取消选中所有复选框。我想用JavaScript或jQuery做到这一点。

<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>


等等....

最佳答案

尝试这个

​$(function(){
    var el=$('input:checkbox[name="city_pref[]"]');
    el.on('change', function(e){
        if($(this).is(':checked')) el.not($(this)).prop('checked', false);
    });
});​


DEMO.

更新:(在澄清问题之后)

$(function(){
    var el=$('input:checkbox[name="city_pref[]"]');
    el.on('change', function(e){
        if($(this).attr('id')!='city_all')
        {
            if($(this).is(':checked')) $('#city_all').prop('checked', false);
        }
        else
        {
            if($(this).is(':checked')) el.not($(this)).prop('checked', false);
        }
    });
});​


DEMO.

更新:(23-07-2012)

I want the functionality, when no checkbox is selected, then All will get selected automatically

Updated Demo.

10-05 20:42
查看更多