Reputation: 107
I'm trying to add text to a div based on which radio button a user checks, but it ends up firing the "else" block no matter which attribute is checked, and displaying "female" every time.
Please help!
<input type="radio" name="gender" class="gender" id="male" value="male">Male<br />
<input type="radio" name="gender" class="gender" id="female" value="female">Female<br />
$(".gender").change(function () {
if ($("#male").attr("checked")) {
$("#content").text("male");
}
else {
$("#content").text("female");
}
});
Upvotes: 3
Views: 9916
Reputation: 79830
Your code would have worked until jQuery 1.8
or lesser. http://jsfiddle.net/Dnd2L/
In latest versions .attr
is for the attributes which was defined in the HTML and .prop
is mapped to the properties of the element which is dynamic and returns the current value.
http://jsfiddle.net/Dnd2L/1/
More information about attr
and prop
- https://stackoverflow.com/a/5876747/297641
Upvotes: 5
Reputation: 1182
or if your radios don't have a class use
$("input[name='gender'][checked='checked']").val();
to get the value of the checked radio. To change which is checked, put the value of the cbx you want checked in val() i.e., ...val("male");
Upvotes: 0
Reputation: 661
You don't particularly need an if since your radio buttons are grouped and no multiple choices are possible.
You might want to use this instead:
$(".gender").change(function () {
$("#content").text($(this).val());
});
JSFiddle: http://jsfiddle.net/3Lsg6/
Upvotes: 0
Reputation: 191749
Use .prop('checked')
rather than .attr('checked')
. The latter is based on the HTML attribute which will always be false because it is not in the DOM. .prop
can be used to check property changes that may not be visible in the DOM.
Upvotes: 7