Skip to content Skip to sidebar Skip to footer

How To I Get The Value Of A Radio Button With Javascript

I need to obtain the value of a radio button using javascript I have a radio group called selection

Solution 1:

Use:

function getRadioValue(name) {
    vargroup = document.getElementsByName(name);

    for (var i=0;i<group.length;i++) {
        if (group[i].checked) {
            returngroup[i].value;
        }
    }

    return'';
}

Application:

var selectedValue = getRadioValue('selection');

Demo:

http://www.jsfiddle.net/tqQWT/

Solution 2:

Although Matt's solution works perfectly fine and solves your immediate problem, I would also recommend that you start looking into a JavaScript library, like JQuery, if you will be frequently querying the DOM.

With JQuery, your solution is a one-liner:

var selectedValue = $("input[name=selection]:checked").val();

Solution 3:

plain javasript:

var selectedValue = document.querySelector('input[name=selection]:checked').value;

Post a Comment for "How To I Get The Value Of A Radio Button With Javascript"