user893970 user893970 - 1 month ago 7
Ajax Question

Getting the selected radio without using "Id" but "name"

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>


Ajax(relavant part of 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);


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)

Answer

Demo: http://jsfiddle.net/majidf/LhDXG/

Markup

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