javascript - jQuery取消选中复选框不起作用

标签 javascript jquery html checkbox

在 StackOverflow 上尝试了多个示例来解决我的问题后,我仍然无法弄清楚我的问题。

我有 3 个复选框:

<input id="pets_dog" class="text" type="checkbox" class="pets" name="pets[]" value="pets_dog"> Dogs</input>
<input id="pets_cats" class="text" type="checkbox" class="pets" name="pets[]" value="pets_cats"> Cats</input>
<input id="pets_none" class="text" type="checkbox" class="pets" name="pets[]" value="pets_no"> None</input>

当“pets_none”被选中时,我需要取消选中其他 2 个复选框,反之亦然。这是我当前的 jQuery 代码:

        $("#pets_none").change(function() {
            if($("#pets_none").attr('checked')) {
            $("#pets_cats").removeAttr('checked');
            $("#pets_dogs").removeAttr('checked');
            } 
        });

我终究无法弄清楚为什么它不起作用,感谢任何帮助。

最佳答案

你的 html 应该是

<input id="pets_dog" class="text pets" type="checkbox" name="pets[]" value="pets_dog" /> Dogs
<input id="pets_cats" class="text pets" type="checkbox" name="pets[]" value="pets_cats" /> Cats
<input id="pets_none" class="text pets" type="checkbox" name="pets[]" value="pets_no" /> None​​​​​​​​​​​

JS

$(function(){
   $("#pets_none").on('change', function(e) {
       if($(this).is(':checked')) {
           $("#pets_dog").attr('checked', false);
           $("#pets_cats").attr('checked', false);
       } 
   });
});

DEMO.

更新: 你已经使用了两次类属性,应该如下所示

<input id="pets_dog" type="checkbox" class="pets text" name="pets[]" value="pets_dog" /> Dogs
<input id="pets_cats" type="checkbox" class="pets text" name="pets[]" value="pets_cats" /> Cats
<input id="pets_none" type="checkbox" class="text pets" name="pets[]" value="pets_no" /> None​

JS

$(function(){
    $(".pets").on('change', function(e) {
        var el=$(this);
        if(el.is(':checked') && el.attr('id')=='pets_none') {
            $(".pets").not(el).attr('checked', false);
        }
        else if(el.is(':checked') && el.attr('id')!='pets_none')
        {
            $("#pets_none").attr('checked', false);
        }  
    });
});

DEMO.

关于javascript - jQuery取消选中复选框不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11066436/

相关文章:

javascript - 在加载 JavaScript 时将值替换为图像

jquery - 移动设备上的 Ajax POST 请求 : cross domain or WS forwarding?

jquery - 在 css 中组织行和列

javascript - 单击时更改 div id

javascript - 固定页脚的问题

javascript - session 超时不断调用 Angular 6 中的函数

c# - Gridview 标题卡住在母版页中不起作用

javascript - 设置间隔不起作用?

php - 清除 php 中的 url 和 javascript 加载顺序问题

javascript - 如何将 HTML 输入光标定位在居中占位符的开头