使用javascript获取单选按钮的值 [英] Getting the value from a radio button using javascript

查看:69
本文介绍了使用javascript获取单选按钮的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有广播输入的HTML表单,并且想用javascript来分析结果。
我在检索JavaScript函数中的表单信息时遇到困难:

  function getResults(formInput){
alert(formInput.question1);
}

其中question1是我单选按钮组的名称。



这会返回object Nodelist,我不知道什么是错误的,我希望它返回1,这是选中时单选按钮的值。 / p>

我不想确定哪个单选按钮被选中,哪个不是,我需要知道与所选单选按钮相关的值。

解决方案

您所指的对象Nodelist 正在返回,因为您拥有共享相同名称的元素组。如果您想查看已检查的单选按钮的值,则需要遍历集合:

  function getResults() {
var radios = document.getElementsByName(question1);

为(var i = 0; i< radios.length; i ++){
if(radios [i] .checked){
alert(radios [i]。值);
休息;





$ b

这里是工作jsFiddle


I have a HTML form with radio inputs and want to use javascript to analyse the results. I am getting stuck at retrieving the form information in my JavaScript function:

function getResults(formInput){
    alert (formInput.question1);
}

Where question1 is the "name" of my radio button group.

This returns "object Nodelist" and I haven't a clue what's wrong, I would expect it to return "1", which is the value of my radio button when selected.

I don't want to work out which radio button is selected and which isn't, I need to know the value associated with the selected radio button.

解决方案

The object Nodelist that you're referring to is being returned because you have a group of elements that share the same name. If you want to see the value of the radio button that's checked, you need to loop through the collection:

function getResults() {
    var radios = document.getElementsByName("question1");

    for (var i = 0; i < radios.length; i++) {       
        if (radios[i].checked) {
            alert(radios[i].value);
            break;
        }
    }
}

Here's a working jsFiddle.

这篇关于使用javascript获取单选按钮的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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