[英]How to get the selected radio button’s value?
I'm having some strange problem with my JS program.我的 JS 程序有一些奇怪的问题。 I had this working properly but for some reason it's no longer working.
我让这个工作正常,但由于某种原因它不再工作。 I just want to find the value of the radio button (which one is selected) and return it to a variable.
我只想找到单选按钮的值(选择了哪个)并将其返回给变量。 For some reason it keeps returning
undefined
.由于某种原因,它不断返回
undefined
。
Here is my code:这是我的代码:
function findSelection(field) {
var test = 'document.theForm.' + field;
var sizes = test;
alert(sizes);
for (i=0; i < sizes.length; i++) {
if (sizes[i].checked==true) {
alert(sizes[i].value + ' you got a value');
return sizes[i].value;
}
}
}
submitForm
: submitForm
:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
HTML: HTML:
<form action="#n" name="theForm">
<label for="gender">Gender: </label>
<input type="radio" name="genderS" value="1" checked> Male
<input type="radio" name="genderS" value="0" > Female<br><br>
<a href="javascript: submitForm()">Search</A>
</form>
This works with any explorer.这适用于任何资源管理器。
document.querySelector('input[name="genderS"]:checked').value;
This is a simple way to get the value of any input type.这是获取任何输入类型的值的简单方法。 You also do not need to include jQuery path.
您也不需要包含 jQuery 路径。
You can do something like this:你可以这样做:
var radios = document.getElementsByName('genderS'); for (var i = 0, length = radios.length; i < length; i++) { if (radios[i].checked) { // do whatever you want with the checked radio alert(radios[i].value); // only one radio can be logically checked, don't check the rest break; } }
<label for="gender">Gender: </label> <input type="radio" name="genderS" value="1" checked="checked">Male</input> <input type="radio" name="genderS" value="0">Female</input>
Edit: Thanks HATCHA and jpsetung for your edit suggestions.编辑:感谢 HATCHA 和 jpsetung 的编辑建议。
document.forms.your-form-name.elements.radio-button-name.value
Since jQuery 1.8, the correct syntax for the query is从 jQuery 1.8 开始,查询的正确语法是
$('input[name="genderS"]:checked').val();
Not $('input[@name="genderS"]:checked').val();
不是
$('input[@name="genderS"]:checked').val();
anymore, which was working in jQuery 1.7 (with the @ ).不再,它在 jQuery 1.7 中工作(使用@ )。
let genderS = Array.from(document.getElementsByName("genderS")).find(r => r.checked).value;
最简单的解决方案:
document.querySelector('input[name=genderS]:checked').value
In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:如果有人正在寻找答案并像我一样来到这里,从 Chrome 34 和 Firefox 33 开始,您可以执行以下操作:
var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);
or simpler:或者更简单:
alert(document.theForm.genderS.value);
refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value参考: https : //developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here's a nice way to get the checked radio button's value with plain JavaScript:这是使用纯 JavaScript 获取选中单选按钮值的好方法:
const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');
// log out the value from the :checked radio
console.log(checked.value);
Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons来源: https : //ultimatecourses.com/blog/get-value-checked-radio-buttons
Using this HTML:使用这个 HTML:
<form name="demo">
<label>
Mario
<input type="radio" value="mario" name="characters" checked>
</label>
<label>
Luigi
<input type="radio" value="luigi" name="characters">
</label>
<label>
Toad
<input type="radio" value="toad" name="characters">
</label>
</form>
You could also use Array Find the checked
property to find the checked item:您还可以使用Array Find the
checked
属性来查找选中的项目:
Array.from(form.elements.characters).find(radio => radio.checked);
Try this尝试这个
function findSelection(field) {
var test = document.getElementsByName(field);
var sizes = test.length;
alert(sizes);
for (i=0; i < sizes; i++) {
if (test[i].checked==true) {
alert(test[i].value + ' you got a value');
return test[i].value;
}
}
}
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
return false;
}
This is pure JavaScript, based on the answer by @Fontas but with safety code to return an empty string (and avoid a TypeError
) if there isn't a selected radio button:这是纯 JavaScript,基于@Fontas 的回答,但如果没有选定的单选按钮,则使用安全代码返回空字符串(并避免
TypeError
):
var genderSRadio = document.querySelector("input[name=genderS]:checked");
var genderSValue = genderSRadio ? genderSRadio.value : "";
The code breaks down like this:代码分解如下:
<input>
type, (b) has a name
attribute of genderS
, and (c) is checked.<input>
类型的控件的引用,(b) 具有name
属性genderS
,并且 (c) 已检查。genderSRadio
variable is truthy if Line 1 finds the control and null/falsey if it doesn't.genderSRadio
变量为真,否则为 null/falsey。 For JQuery, use @jbabey's answer, and note that if there isn't a selected radio button it will return undefined
.对于 JQuery,请使用 @jbabey 的答案,并注意如果没有选定的单选按钮,它将返回
undefined
。
Edit: As said by Chips_100 you should use :编辑:正如 Chips_100 所说,你应该使用:
var sizes = document.theForm[field];
directly without using the test variable.直接不使用测试变量。
Old answer:旧答案:
Shouldn't you eval
like this ?你不应该
eval
这样呢?
var sizes = eval(test);
I don't know how that works, but to me you're only copying a string.我不知道它是如何工作的,但对我来说你只是在复制一个字符串。
First, shoutout to ashraf aaref , who's answer I would like to expand a little.首先,对ashraf aaref 大喊大叫,我想稍微扩展一下他的回答。
As MDN Web Docs suggest, using RadioNodeList
is the preferred way to go:正如 MDN Web Docs 所建议的,使用
RadioNodeList
是首选方式:
// Get the form
const form = document.forms[0];
// Get the form's radio buttons
const radios = form.elements['color'];
// You can also easily get the selected value
console.log(radios.value);
// Set the "red" option as the value, i.e. select it
radios.value = 'red';
One might however also select the form via querySelector
, which works fine too:然而,也可以通过
querySelector
选择表单,这也可以正常工作:
const form = document.querySelector('form[name="somename"]')
However , selecting the radios directly will not work, because it returns a simple NodeList
.然而,直接选择电台将无法正常工作,因为它返回一个简单的
NodeList
。
document.querySelectorAll('input[name="color"]')
// Returns: NodeList [ input, input ]
While selecting the form first returns a RadioNodeList
选择表单时首先返回一个
RadioNodeList
document.forms[0].elements['color']
// document.forms[0].color # Shortcut variant
// document.forms[0].elements['complex[naming]'] # Note: shortcuts do not work well with complex field names, thus `elements` for a more programmatic aproach
// Returns: RadioNodeList { 0: input, 1: input, value: "red", length: 2 }
This is why you have to select the form first and then call the elements
Method.这就是为什么你必须先选择表单,然后调用
elements
方法。 Aside from all the input
Nodes, the RadioNodeList
also includes a property value
, which enables this simple manipulation.除了所有
input
节点之外, RadioNodeList
还包括一个属性value
,它可以实现这种简单的操作。
Reference: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value参考: https : //developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value
Here is an Example for Radios where no Checked="checked" attribute is used这是一个没有使用Checked="checked"属性的 Radios 示例
function test() {
var radios = document.getElementsByName("radiotest");
var found = 1;
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
alert(radios[i].value);
found = 0;
break;
}
}
if(found == 1)
{
alert("Please Select Radio");
}
}
DEMO : http://jsfiddle.net/ipsjolly/hgdWp/2/ [ Click Find without selecting any Radio ]演示: http : //jsfiddle.net/ipsjolly/hgdWp/2/ [点击查找而不选择任何收音机]
Source (from my blog): http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html来源(来自我的博客): http : //bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
Putting Ed Gibbs ' answer into a general function:将Ed Gibbs的答案放入一般的 function 中:
function findSelection(rad_name) {
const rad_val = document.querySelector('input[name=' + rad_name + ']:checked');
return (rad_val ? rad_val.value : "");
}
Then you can do findSelection("genderS");
然后你可以做
findSelection("genderS");
lets suppose you need to place different rows of radio buttons in a form, each with separate attribute names ('option1','option2' etc) but the same class name.让我们假设您需要在表单中放置不同行的单选按钮,每个单选按钮具有单独的属性名称('option1'、'option2' 等)但具有相同的类名称。 Perhaps you need them in multiple rows where they will each submit a value based on a scale of 1 to 5 pertaining to a question.
也许您需要它们在多行中,每行都将根据与问题相关的 1 到 5 的比例提交一个值。 you can write your javascript like so:
你可以像这样写你的javascript:
<script type="text/javascript">
var ratings = document.getElementsByClassName('ratings'); // we access all our radio buttons elements by class name
var radios="";
var i;
for(i=0;i<ratings.length;i++){
ratings[i].onclick=function(){
var result = 0;
radios = document.querySelectorAll("input[class=ratings]:checked");
for(j=0;j<radios.length;j++){
result = result + + radios[j].value;
}
console.log(result);
document.getElementById('overall-average-rating').innerHTML = result; // this row displays your total rating
}
}
</script>
I would also insert the final output into a hidden form element to be submitted together with the form.我还将最终输出插入到一个隐藏的表单元素中,以便与表单一起提交。
Using a pure javascript, you can handle the reference to the object that dispatched the event.使用纯 javascript,您可以处理对调度事件的对象的引用。
function (event) {
console.log(event.target.value);
}
document.querySelector('input[name=genderS]:checked').value
If it is possible for you to assign a Id for your form element(), this way can be considered as a safe alternative way (specially when radio group element name is not unique in document):如果您可以为表单 element() 分配 Id,则可以将这种方式视为一种安全的替代方式(特别是当无线电组元素名称在文档中不唯一时):
function findSelection(field) {
var formInputElements = document.getElementById("yourFormId").getElementsByTagName("input");
alert(formInputElements);
for (i=0; i < formInputElements.length; i++) {
if ((formInputElements[i].type == "radio") && (formInputElements[i].name == field) && (formInputElements[i].checked)) {
alert(formInputElements[i].value + ' you got a value');
return formInputElements[i].value;
}
}
}
HTML: HTML:
<form action="#n" name="theForm" id="yourFormId">
我喜欢使用括号从输入中获取值,它比使用点更清晰。
document.forms['form_name']['input_name'].value;
I prefer to use a formdata object as it represents the value that should be send if the form was submitted.我更喜欢使用formdata 对象,因为它表示提交表单时应该发送的值。
let formData = new FormData(document.querySelector("form")); console.log(`The value is: ${formData.get("choice")}`);
<form> <p>Pizza crust:</p> <p> <input type="radio" name="choice" value="regular" > <label for="choice1id">Regular crust</label> </p> <p> <input type="radio" name="choice" value="deep" checked > <label for="choice2id">Deep dish</label> </p> </form>
<input type=radio name=rdbExampleInfo id=rdbExamples value="select 1">
<input type=radio name=rdbExampleInfo id=rdbExamples value="select 2">
<input type=radio name=rdbExampleInfo id=rdbExamples value="select 3">
<input type=radio name=rdbExampleInfo id=rdbExamples value="select 4">
etc then use just等然后使用
$("#rdbExamples:checked").val()
Or或者
$('input[name="rdbExampleInfo"]:checked').val();
var value = $('input:radio[name="radiogroupname"]:checked').val();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.