最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery radio button "checked" attribute not firing - Stack Overflow

programmeradmin3浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论