简体   繁体   中英

Check a box with jQuery when condition is met

I have five opt-in check boxes and an unsubscribe checkbox. When I click an opt-in checkbox, if none of the opt-in checkboxes remain checked, the unsubscribe checkbox is supposed to be automatically checked. If I then check one of the opt-in boxes, the unsubscribe checkbox is supposed by be automatically unchecked.

The automatic unchecking of the unsubscribe checkbox works just fine. What I can't get to work is the automatic checking of the unsubscribe checkbox when none of the opt-in checkboxes is checked.

var $jQ = jQuery.noConflict();

$jQ("#Unsubscribed").click(function(event) {
    opt_ins_unchecked = $(":checkbox" ).not('#Unsubscribed').not(':checked').length;
    if (opt_ins_unchecked == 5 && !$jQ("#Unsubscribed").is(':checked')){
        event.preventDefault();

    } else {
            $jQ("input[name=Opt-In_Premium_Content],input[name=Opt-In_Product_Updates],input[name=Opt-In_Industry_Best_Practices],input[name=Opt-In_Events_Webinars],input[name=Opt-In_Education_Training]").attr("checked", false);
    }
});

$jQ("#Opt-In_Premium_Content, #Opt-In_Product_Updates, #Opt-In_Industry_Best_Practices, #Opt-In_Events_Webinars, #Opt-In_Education_Training").click(function() {
    opt_ins_unchecked = $(":checkbox" ).not('#Unsubscribed').not(':checked').length;
    if (opt_ins_unchecked == 5){
        $jQ("#Unsubscribed").attr("checked", true);
    }

    if (opt_ins_unchecked != 0){
        $jQ("#Unsubscribed").attr("checked", false);
    }
});

Why isn't the $jQ("#Unsubscribed").attr("checked", true); line run when I have no opt-in checkboxes checked? How can I get the unsubscribe box to be checked when I uncheck all of the opt-in checkboxes?

Use .prop() to set the checked state instead of .attr()

$jQ("#Unsubscribed").prop("checked", true);

Try

var $unsubscribed = $jQ("#Unsubscribed");
var $checks = $jQ("#Opt-In_Premium_Content, #Opt-In_Product_Updates, #Opt-In_Industry_Best_Practices, #Opt-In_Events_Webinars, #Opt-In_Education_Training");

$checks.change(function () {
    $unsubscribed.prop("checked", $checks.filter(':checked').length == 0);
});

jQuery 1.6+ recommended prop() instead of attr():

Use the new .prop() function:

$jQ('#Unsubscribed').prop('checked', true);
$jQ('#Unsubscribed').prop('checked', false);

jQuery 1.5 and below you can use attr as prop() was not available.

or you can use any jQuery:

$jQ("#Unsubscribed").removeAttr('checked');

事实证明这是行不通的,因为两个if语句都评估为true

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