Reputation: 5284
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?
Upvotes: 1
Views: 724
Reputation: 5284
It turns out it wasn't working because both the if
statements were evaluating to true
Upvotes: 0
Reputation: 388436
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);
});
Upvotes: 1
Reputation: 28588
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');
Upvotes: 0