简体   繁体   English

选择单选按钮时,选中并禁用复选框

[英]When Radio Button is selected, check and disabled checkbox

I'm still learning jquery but this is what I want 我还在学习jquery,但这就是我想要的

If the radio button with the value of '16' is selected I want the checkbox with the class newsletter selected and then made unable to uncheck. 如果选择了值为“16”的单选按钮,我想要选中类新闻稿的复选框,然后无法取消选中。

If the radio button with the value 16 is deselected I want to be able to once again use the checkbox. 如果取消选择值为16的单选按钮,我希望能够再次使用该复选框。

Without seeing your HTML, I'm assuming a simple case. 没有看到你的HTML,我假设一个简单的案例。 Here's some short jQuery to do what you asked for: 这里有一些简短的jQuery来做你要求的:

$('input[type="radio"]').click(function() {
    $('input.newsletter').attr({
        'checked': $(this).val() == 16,
        'disabled': $(this).val() == 16
    });
});​

jsFiddle example . jsFiddle例子

$("input[type=radio][name=<your radio button set name here>]").changed( function () {
    if ($("input[type=radio][name=<your radio button set name here>]").val() == "16") {
        $("input[type=checkbox].newsletter").attr('checked', 'checked');
        $("input[type=checkbox].newsletter").attr('disabled', 'disabled'); //this is one way to make it not unselectable
    }
    else {
        $("input[type=checkbox].newsletter").removeAttr('disabled');
    }
}

Another way to make it not able to be unselected is in the place of the 2nd line in under the if above (the one with the comment next to it) put stayChecked = true; 使其无法取消选择的另一种方法是在上面的if下面的第二行的位置(旁边有注释的那个)put stayChecked = true; and put stayChecked = false; 并把stayChecked = false; in place of the $(...).removeAttr('disabled'); 代替$(...).removeAttr('disabled'); . Then make another function like the following: 然后创建另一个函数,如下所示:

$("input[type=checkbox].newsletter").changed( function () {
    if (stayChecked) {
        $(this).attr('checked', 'checked');
    }
});

Note: you should either declare var stayChecked somewhere outside the two functions on a common level (ie on the script level or inside the parent function if they are declared inside, let's say, the $(document).ready() function). 注意:你应该在一个公共级别上的两个函数之外的某个地方声明var stayChecked (即在脚本级别或父函数内部,如果它们在内部声明,比如说,$(document).ready()函数)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM