Reputation: 25
I'm new to JQuery and struggling to fix a problem in which I'm trying to disable a number of checkboxes when one Main checkbox is checked.
I have a form which contains 1 primary checkbox and 3 secondary checkboxes. When the primary checkbox is checked, all the other secondary checkboxes are disabled but must have a checked status by default. And when the primary checkbox is unchecked then all the other secondary checkboxes which were disabled turn to enabled and must all be checked. By default, when a user arrives on the form: the primary checkbox must be checked and thus, the other 3 must be checked and disabled.
this is my code:
<s:checkbox id="primary_CB" name="primaryCB" value="true"/>Primary checkbox
<s:checkbox cssClass="secondary_CB" name="secondary_CB1"/>Secondary checkbox1
<s:checkbox cssClass="secondary_CB" name="secondary_CB2"/>Secondary checkbox2
<s:checkbox cssClass="secondary_CB" name="secondary_CB3"/>Secondary checkbox3
my JQuery code:
$('#primary_CB').click(function () {
if ($(this).attr('checked')) {
$(".secondary_CB").attr('disabled', 'disabled');
} else {
$(".secondary_CB").removeAttr('disabled');
}
});
however my code works in strange way, when I'm on the form for the first time, all 4 checkboxes are checked, none disabled. Only when I uncheck/check again the primary checkbox that the disable function takes place. Also, when disable again all secondary checkboxes go unchecked automatically.
Can anyone please help?
Upvotes: 0
Views: 4278
Reputation: 2015
This should work, if I understand your problem correctly:
$("#primary_CB").click(function() {
$("input.secondary_CB").prop("disabled", !this.checked);
});
for jQuery below 1.6
$("#primary_CB").click(function() {
$("input.secondary_CB").attr("disabled", !this.checked);
});
Upvotes: 1
Reputation: 991
$('#primary_CB').click(function () {
if ( !$(this).is ( ":checked" ) )
{
$(".secondary_CB").attr ( "disabled" , true );
} else {
$(".secondary_CB").removeAttr ( "disabled" );
}
});
Upvotes: 0