How can we access the value of a radio button using the DOM?

后端 未结 12 1908
鱼传尺愫
鱼传尺愫 2020-12-05 15:25

How can we access the value of a radio button using the DOM?

For eg. we have the radio button as :



        
12条回答
  •  北荒
    北荒 (楼主)
    2020-12-05 15:31

    Just to "generify" Canavar's very helpful function:

    function getRadioValue(theRadioGroup)
    {
        var elements = document.getElementsByName(theRadioGroup);
        for (var i = 0, l = elements.length; i < l; i++)
        {
            if (elements[i].checked)
            {
                return elements[i].value;
            }
        }
    }
    

    ... which would now be referenced thusly:

    getRadioValue('sex');
    

    Strange that something like this isn't already a part of prototype.js.

提交回复
热议问题