通过 JavaScript 验证单选按钮 [英] Radio button validation through JavaScript

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

问题描述

我有以下表格:

<form name="survey1" action="add5up.php" method="post" onsubmit="return validateForm()">
<div id="question">Q1) My programme meets my expectations</div><br />
Always<INPUT  TYPE = 'Radio' Name ='q1'  value= 'a'> 
Usually<INPUT  TYPE = 'Radio' Name ='q1' value= 'b'> 
Rarely<INPUT  TYPE = 'Radio' Name ='q1' value= 'c'> 
Never<INPUT  TYPE = 'Radio' Name ='q1' value= 'd'> 
<input type="submit" value="addData" />
</form>

我正在尝试验证是否选择了 Radio 按钮.

I am trying to validate whether a Radio button has been selected.

我正在使用的代码:

<script type="text/javascript">
function validateForm()
{
if( document.forms["survey1"]["q1"].checked)
{
    return true;
}

else
{
    alert('Please answer all questions');
    return false;
}
}
</script>

这不起作用.有什么想法吗?

This is not working. Any ideas?

推荐答案

当使用单选按钮时,你必须检查它们是否被选中,因为 javascript 将它们作为数组威胁:

When using radiobuttons you have to go through to check if any of them is checked, because javascript threats them as an array:

<script type="text/javascript">
function validateRadio (radios)
{
    for (i = 0; i < radios.length; ++ i)
    {
        if (radios [i].checked) return true;
    }
    return false;
}

function validateForm()
{
    if(validateRadio (document.forms["survey1"]["q1"]))
    {
        return true;
    }
    else
    {
        alert('Please answer all questions');
        return false;
    }
}
</script>

问候

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

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