Home > Web Front-end > JS Tutorial > js如何获取radio单选框选中的值

js如何获取radio单选框选中的值

WBOY
Release: 2016-06-01 09:54:51
Original
6922 people have browsed it

js中一般使用遍历的方法获取radio被选中的值,遍历判断每个Radio是否被选中,如果是,再取其值.

<code class="language-html"><form id="userlist" method="post" action="option.php">
    <input type="radio" name="userid" value="1">1
    <input type="radio" name="userid" value="2">2
    <input type="radio" name="userid" value="3">3
</form>
<script language="javascript">
    function usubmit(action){
        var radionum = document.getElementById("userlist").userid;
        for(var i=0;i<radionum.length;i++){
        if(radionum[i].checked){
            userid = radionum[i].value
        }
    }
    window.location.href='option.php?action='+action+'&userid='+userid;
}
</script></code>
Copy after login

这里有两个要注意的地方:一个是如何取值,一个是如何遍历

<code class="language-javascript">document.getElementById("userlist").userid;</code>
Copy after login

这是根据form的id再取其中控件元素的name取值的方法。

document.getElementById("userlist").userid;获取的是一个数组,该数组中的元素是该dom树中所有name为userid的元素,即使只有一个radio,也是一个只包含一个元素的数组,然后我们遍历这个数组,如果数组中某一个radio的checked属性为true,则表示该radio被选中。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template