Javascript 如何从表单输入 type=radio 中获取值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8666229/
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
How to get value from form input type=radio?
提问by Hai Truong IT
<input type="radio" value="0" name="type" checked="yes" />
<label>Type 0</label>
<input type="radio" value="1" name="type" />
<label>Type 1</label>
and js:
和js:
var type = this.type.value;
alert(type);
How to fix it ?
如何解决?
回答by nnnnnn
In what context does that JS code run? If this
is the radio button in question then this.value
will return the value.
该 JS 代码在什么上下文中运行?如果this
是有问题的单选按钮,this.value
则将返回该值。
If your question is "How do I get the value of the currently selected radio button in the 'type' group?" then you may need to do something like this:
如果您的问题是“如何获取‘类型’组中当前选定的单选按钮的值?” 那么你可能需要做这样的事情:
function getCheckedRadioValue(radioGroupName) {
var rads = document.getElementsByName(radioGroupName),
i;
for (i=0; i < rads.length; i++)
if (rads[i].checked)
return rads[i].value;
return null; // or undefined, or your preferred default for none checked
}
var checkedValue = getCheckedRadioValue("type");
(It would be easier with .querySelector()
or .querySelectorAll()
, but not all browsers support them.)
(使用.querySelector()
或会更容易.querySelectorAll()
,但并非所有浏览器都支持它们。)
回答by ton
Just use selectors.
只需使用选择器。
With jquery
使用 jquery
$("input[name=type]:checked").val();
Or without jquery:
或者没有 jquery:
document.querySelector("input[name=type]:checked").value;
回答by Purag
Just use this.value
instead of this.type.value
.
只需使用this.value
代替this.type.value
.
this.value
will select the value associated with the value
attribute of the input. (That's a mouthful).
this.value
将选择与value
输入属性关联的值。(那是一口)。