How to I get the value of a radio button with javascript

前端 未结 2 824
渐次进展
渐次进展 2020-12-06 22:39

I need to obtain the value of a radio button using javascript

I have a radio group called selection



        
相关标签:
2条回答
  • 2020-12-06 22:57

    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();
    
    0 讨论(0)
  • 2020-12-06 23:16

    Use:

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

    Application:

    var selectedValue = getRadioValue('selection');
    

    Demo:

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

    0 讨论(0)
提交回复
热议问题