JQuery radio button "checked" attribute not firing
I'm trying to add text to a div based on which the user is checking the radio button, but it ends up running 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");
}
});
Use .prop('checked')
instead .attr('checked')
. The latter is based on an HTML attribute which will always be false because it is not in the DOM. .prop
can be used to check for property changes that might not be visible in the DOM.
http://jsfiddle.net/Xxuh8/
Your code would work before jQuery 1.8
or less. http://jsfiddle.net/Dnd2L/
In recent versions .attr
for attributes that were defined in HTML, it .prop
maps to the properties of a dynamic element and returns the current value.
http://jsfiddle.net/Dnd2L/1/
More information on attr
and prop
- fooobar.com/questions/463 / ...
You don't particularly need it if your radio buttons are grouped and multiple options are not possible.
You can use this instead:
$(".gender").change(function () {
$("#content").text($(this).val());
});
JSFiddle: http://jsfiddle.net/3Lsg6/
or if your radios don't use the class
$("input[name='gender'][checked='checked']").val();
to get the value of the checked radio. To change this, put the cbx value you want to check in val (), i.e....val("male");