Javascript JQuery:获取单选按钮值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4139437/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery: get radio button value
提问by StaceyH
I have the following HTML:
我有以下 HTML:
HTML:
HTML:
<input type="radio" name="abc" value="0" selected="selected" style="display:none" />
<input type="radio" name="abc" value="1" />1+
<input type="radio" name="abc" value="2" />2+
<input type="radio" name="abc" value="3" />3+
JQuery to get the selected radio button
JQuery 获取选中的单选按钮
$('input:radio[name=abc]:checked').val();
Why doesn't the code above work on page load, BEFORE a user selected a radio button? It's strange because the code above does work AFTER a user selected a radio button.
为什么上面的代码在页面加载时不起作用,在用户选择单选按钮之前?这很奇怪,因为上面的代码在用户选择一个单选按钮后确实有效。
It seems to me that I have set the default radio button value to be 0
, but if you
在我看来,我已将默认单选按钮值设置为0
,但是如果您
Meaning, if the radio button value is selected, return the selected value - otherwise, return 0 (when no value has been selected)
意思是,如果选择了单选按钮值,则返回所选值 - 否则,返回 0(未选择值时)
回答by ?ime Vidas
You are using the wrong attribute. For radio buttons you have to use the checked
attribute and not the selected
attribute.
您使用了错误的属性。对于单选按钮,您必须使用checked
属性而不是selected
属性。
<input type="radio" checked="checked">
or just:
要不就:
<input type="radio" checked>
回答by Ashish Babu
First correct the attribute to checked and remove selected attribute which is wrong and then use the following code. t will get the selected value of the radiobutton at button click. ex for list
首先更正属性以检查并删除错误的选定属性,然后使用以下代码。t 将在单击按钮时获取单选按钮的选定值。清单前列
$("#btn").click(function() {
$('input[type="radio"]:checked').val();
});
回答by Galen
Radio has the attribute checked
, not selected
Radio 有这个属性checked
,不是selected
<input type="radio" name="abc" value="0" checked="checked" style="display:none" />
<input type="radio" name="abc" value="1" />1+
<input type="radio" name="abc" value="2" />2+
<input type="radio" name="abc" value="3" />3+