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
4 Answers
Reset to default 7Use .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
版权声明:本文标题:javascript - jQuery radio button "checked" attribute not firing - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1740257460a2249641.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论