admin管理员组

文章数量:1247209

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

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");
    }
});
Share Improve this question asked Feb 12, 2013 at 20:09 bmcsweebmcswee 1072 silver badges6 bronze badges 1
  • I suppose you can't set the value directly – Alexander Commented Feb 12, 2013 at 20:19
Add a ment  | 

4 Answers 4

Reset to default 7

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/Xxuh8/

Your code would have worked until jQuery 1.8 or lesser. http://jsfiddle/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/Dnd2L/1/

More information about attr and prop - https://stackoverflow./a/5876747/297641

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/3Lsg6/

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

本文标签: javascriptjQuery radio button quotcheckedquot attribute not firingStack Overflow