获取选定的单选而不使用"编号"但"名称"而不、单选、编号、名称

2023-09-10 21:25:01 作者:一个人的女王

我试图用document.getElementByName('nameOfradio')即可选择单选按钮,因为所有的单选按钮的名称相同。但是,什么都没有发生。我想同样的事情的document.getElementById('nameOfradio')和工作well.However,我不得不放弃唯一的ID来进行的单选按钮。这样,原来丑陋的,当我有20个单选按钮。其结果是,我想要的东西正在一条捷径。我怎样才能所选单选按钮的使用他们的名的价值? codeS;

I was trying to get selected radio button by using "document.getElementByName('nameOfradio')" because all of the radio buttons share the same name. But, nothing happened. I tried the same thing with document.getElementById('nameOfradio') and worked well.However, I had to give unique id for all of the radio buttons. So that, it turns ugly when i have 20 radio buttons. As a result, what I wanted is making a shortcut. How can i get the value of selected radio button by using their "name"? Codes;

HTML

<input type="radio" name="nameOfradio" value="onm1" /> 1
<input type="radio" name="nameOfradio" value="onm2" /> 2

<input type='button' onclick='radio3()' value='Submit' />
</form>

阿贾克斯(radio3的初步认识部分())

var radioPushed = document.getElementByName('nameOfradio').value;

var queryString = "?radioPushed=" + radioPushed;//to send the value to another file
ajaxRequest.open("GET", "radio_display.php" + queryString, true);
ajaxRequest.send(null);

正如我所说的document.getElementById工作,但它需要太多的工作:(我怎样才能使它simplier使用的单选按钮的共同特点,而没有给他们唯一的ID?简短说明理由。我不能让这将是非常有帮助的(在JavaScript和Ajax新)

As i said document.getElementById worked but it requires too much work:( How can i make it simplier by using common feature of radio buttons, instead of giving them unique id? A short explanation why i could not make it would be very helpful(new in javascript and ajax)

推荐答案

演示: http://jsfiddle.net / majidf / LhDXG /

标记

Sex:<br/> 
<input type="radio" name="gender" value="male" /> Male<br/>
<input type="radio" name="gender" value="female" /> Female
<br/>
Age group:<br/> 
<input type="radio" name="ageGroup" value="0-3" /> 0 to 3<br/>
<input type="radio" name="ageGroup" value="3-5" /> 3 to 5<br/>
<input type="radio" name="ageGroup" value="5-10" /> 5 to 10<br/>

<button onclick="getValues();">Get values</button>

JS

function getRVBN(rName) {
    var radioButtons = document.getElementsByName(rName);
    for (var i = 0; i < radioButtons.length; i++) {
        if (radioButtons[i].checked) return radioButtons[i].value;
    }
    return '';
}

function getValues() {
    var g = getRVBN('gender');
    var a = getRVBN('ageGroup');
    alert(g + ' ' + a);
}