简体   繁体   中英

When Radio Button is selected, check and disabled checkbox

I'm still learning jquery but this is what I want

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.

If the radio button with the value 16 is deselected I want to be able to once again use the checkbox.

Without seeing your HTML, I'm assuming a simple case. Here's some short jQuery to do what you asked for:

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

jsFiddle example .

$("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; and put stayChecked = false; in place of the $(...).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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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