如何找到纯JavaScript的单选按钮的值? [英] How to find the value of a radio button with pure javascript?

查看:88
本文介绍了如何找到纯JavaScript的单选按钮的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<input checked=checked type="radio" name="colors" value="red" />Red
<input type="radio" name="colors" value="green" />Green
<input type="radio" name="colors" value="blue" />Blue

鉴于上述情况,我设置了默认选中的红色按钮(所以我给它 checked = checked 属性。如果我在该输入元素上调用 .checked ,它将始终返回true,即使选择了另一个选项。

Given the above, I set the red button to be selected by default (so I give it the checked=checked attribute. With this, if I ever call .checked on that input element, it will always return true, even if another option is selected.

在普通的javascript(没有jQuery)中,你怎么能得到实际选定的选项?

In plain javascript (no jQuery), how can you get the actual selected option?

推荐答案



Try this:

var options = document.getElementsByName("colors");
if (options) {
    for (var i = 0; i < options.length; i++) {
        if (options[i].checked){
             alert(options[i].value);
        }
    }
}

亩使用jQuery更容易......只是说。

Would be so much easier with jQuery though... just saying.

这篇关于如何找到纯JavaScript的单选按钮的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆