如何在 jquery 中选中/取消选中复选框时执行事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/917318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:07:11  来源:igfitidea点击:

how to perform events when a checkbox is checked/unchecked in jquery

jquery

提问by n00bstackie

I have the following jquery code which works fine.

我有以下 jquery 代码可以正常工作。

$('#onlyTwo').click(function() {
                $("#textarea3").attr("disabled", true);
                $("#textarea4").attr("disabled", true);
                $("#radio3").attr("disabled", true);
                $("#radio4").attr("disabled", true);
                return true;
            });

This is making some fields disabled when 'onlyTwo' checkbox is clicked. How can i make these fields enabed again when 'onlyTwo' checkbox is unchecked...

这会在单击“onlyTwo”复选框时禁用某些字段。取消选中“onlyTwo”复选框时,如何使这些字段再次启用...

basically i want to know how to find out whether a checkbox is checked or not

基本上我想知道如何找出复选框是否被选中

回答by mkoryak

or

或者

$('#onlyTwo').click(function(){
   var stuff = $("#textarea3,  #textarea4, #radio3, #radio4");
   stuff.attr("disabled", $(this).is(":checked"));
});

回答by coma

$('#onlyTwo').change(function() {
    $('.disableMe').attr('disabled', $(this).is(':checked'));
});

so you need to add 'disableMe' class to all the inputs, textareas, selects... that you wish to disable.

因此,您需要将“disableMe”类添加到您希望禁用的所有输入、文本区域、选择...。

回答by TJ L

$('#onlyTwo').click(function() {
     var elements = ['textarea3', 'textarea4', 'radio3', 'radio4'];
     var checked = $(this).attr('checked');

     jQuery.each(elements, function(element) {
       if (checked) {
         $('#'+element).attr('disabled', true);
       } else {
         $('#'+element).removeAttr('disabled');
       }
     });
})

Thats a simple solution to toggle the disabled attribute on all the elements you want when $('#onlyTwo')is checked.

这是一个简单的解决方案,可以在$('#onlyTwo')选中时在您想要的所有元素上切换禁用属性。

Fixed array problems, lol this was full of little bugs.

修复了数组问题,哈哈,这充满了小错误。