Reputation: 48696
I seem to be having an issue selecting a radio button using jQuery. I put together a simple Fiddle here to demonstrate the issue. Here is my HTML:
<div id="divRadioButtons">
<div style="width: 600px; margin: 5px auto;">
<div style="display: inline"><input type="radio" name="activeStatus" value="Active" id="rbActiveActive" checked="checked">Active</div>
<div style="display: inline"><input type="radio" name="activeStatus" value="Inactive" id="rbActiveInactive">Inactive</div>
<div style="display: inline"><input type="radio" name="activeStatus" value="ComingSoon" id="rbActiveComingSoon">Coming Soon</div>
</div>
</div>
<div style="display: inline-table">
<input type="button" value="Active" id="btnActive" />
</div>
<div style="display: inline-table">
<input type="button" value="Inactive" id="btnInactive" />
</div>
And here is my jQuery:
$(function() {
Reset();
$('#btnActive').click(function() {
Reset();
$('#rbActiveActive').attr('checked', true);
$('#rbActiveInactive').attr('checked', false);
$('#rbActiveComingSoon').attr('checked', false);
$('#divRadioButtons').show();
});
$('#btnInactive').click(function() {
Reset();
$('#rbActiveActive').attr('checked', false);
$('#rbActiveInactive').attr('checked', true);
$('#rbActiveComingSoon').attr('checked', false);
$('#divRadioButtons').show();
});
});
function Reset()
{
$('#divRadioButtons').hide();
$('#rbActiveActive').attr('checked', false);
$('#rbActiveInactive').attr('checked', false);
$('#rbActiveComingSoon').attr('checked', false);
}
When I click on the Active
button, I want the active radio button to be checked. When I click on the Inactive
button, I want the Inactive radio button to be checked.
The issue is really weird because check this out. If I run my fiddle and click the Inactive
button, it works. But if I click the Inactive
button a second time (or third, or fourth time), it deselects it and never works again. If I run my fiddle and select the Active
button, it never works, even though the button code is identical!
Can someone please point me in the right direction? I seem to be tearing my hair out at this issue.
Upvotes: 0
Views: 57
Reputation: 207919
Simple, use .prop()
instead of .attr()
.
As the docs for .prop()
states:
Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.
and...
the most important concept to remember about the checked attribute is that it does not correspond to the checked property. The attribute actually corresponds to the defaultChecked property and should be used only to set the initial value of the checkbox. The checked attribute value does not change with the state of the checkbox, while the checked property does.
Upvotes: 3