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");
}
});
source to share
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 / ...
source to share
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/
source to share