将 HTML 单选按钮值传递给 javascript 变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15600465/
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
passing HTML radio button value to a javascript variable
提问by Rayan Sp
I wonder if anyone can help me out, I'm stuck where I need to write a little code that goes like this.
我想知道是否有人可以帮助我,我被困在需要编写像这样的小代码的地方。
Question : did you like the training?
<input type="radio" name="q4" value="Yes">Yes
<input type="radio" name="q4" value="No">No
whatever is checked I want to pass it to a javascript variable.
无论检查什么,我都想将它传递给一个 javascript 变量。
回答by Sachin
You can try this using Jquery.
您可以使用 Jquery 尝试此操作。
$('input[name="q4"]:checked').val();
回答by dfsq
I think you could do something like this:
我认为你可以做这样的事情:
var ch = document.getElementsByName('q4');
for (var i = ch.length; i--;) {
ch[i].onchange = function() {
alert(this.value);
}
}
So you subscribe to to change event and can use selected value somehow.
因此,您订阅更改事件并可以以某种方式使用选定的值。
Alternatively you can use querySelector(querySelectorAll) methods. Here is an example of how you can get checked element value:
或者,您可以使用querySelector( querySelectorAll) 方法。以下是如何获取已检查元素值的示例:
var checked = document.querySelector('[name="q4"]:checked');