一尘不染

JavaScript 如何获得所选单选按钮的值?

javascript

我的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>

阅读 384

收藏
2020-04-25

共1个答案

一尘不染

您可以执行以下操作:

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>

编辑:感谢HATCHA和jpsetung的编辑建议。

2020-04-25