Getting the selected radio without using “Id” but “name”

后端 未结 6 672
逝去的感伤
逝去的感伤 2020-12-19 03:17

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

6条回答
  •  佛祖请我去吃肉
    2020-12-19 03:39

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

    Markup

    Sex:
    Male
    Female
    Age group:
    0 to 3
    3 to 5
    5 to 10

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

提交回复
热议问题