如何获取选中的单选按钮的值?

2022-01-21 00:00:00 for-loop radio-button javascript html

我的 JS 程序出现了一些奇怪的问题.我让这个工作正常,但由于某种原因它不再工作.我只想找到单选按钮的值(选择了哪个)并将其返回给变量.由于某种原因,它一直返回 undefined.

I’m having some strange problem with my JS program. 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.

这是我的代码:

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;
        }
    }
}

提交表单:

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>

推荐答案

你可以这样做:

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>

jsfiddle

感谢 HATCHA 和 jpsetung 的编辑建议.

Thanks HATCHA and jpsetung for your edit suggestions.

相关文章