我的JS程序有一些奇怪的问题。我有这个工作正常,但由于某种原因,它不再工作。我只是想找到单选按钮的值(其中一个被选中)并将其返回给一个变量。由于某种原因,它总是返回undefined。
这是我的代码:
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:
function submitForm() {
var genderS = findSelection("genderS");
alert(genderS);
}
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>
这里是一个没有使用Checked=" Checked "属性的无线电示例
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");
}
}
演示:http://jsfiddle.net/ipsjolly/hgdWp/2/[点击查找,不选择任何电台]
来源(来自我的博客):http://bloggerplugnplay.blogspot.in/2013/01/validateget-checked-radio-value-in.html
这里有一个很好的方法来获得选中的单选按钮的值与纯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);
来源:https://ultimatecourses.com/blog/get-value-checked-radio-buttons
使用这个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>
你也可以使用Array Find the checked属性来查找被选中的项:
Array.from(form.elements.characters).find(radio => radio.checked);