jQuery radio button "checked" attribute not firing

bmcswee picture bmcswee · Feb 12, 2013 · Viewed 9.8k times · Source

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");
    }
});

Answer

Explosion Pills picture Explosion Pills · Feb 12, 2013

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.

http://jsfiddle.net/Xxuh8/