Javascript单选按钮组验证 [英] Javascript Radiobutton Group Validation

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

问题描述

我希望您能开发一个javascript函数,以验证是否选择了以下单选按钮组(IDType)之一,并检查了哪个值,并在未选择单选按钮的情况下查看了(ValidationError)分区中的错误消息??

I would like your help to develop a javascript function to validate if one of the following radiobutton group (IDType) is selected and which value is checked and view error message in (ValidationError) division in case no radio button selected ??

<td>
<div>
<span>
<input type="radio" name="IDType" id="IDType" value="IDtype1"/>
ID Type 1
<input type="radio" name="IDType" id="IDType" value="IDtype2"/>
ID Type 2
</span>
<div id="ValidationError" name="ValidationError">
&nbsp;
</div>
</div>
</td>

感谢您的帮助.....

Thanks for your help.....

推荐答案

首先,正如我的同事所说,两个单选按钮不能具有相同的ID("IDType").

First of all, as said my collegues, you cannot have the same id ("IDType") for both your radio buttons.

这是仅使用javascript的解决方案,没有任何jquery.

Here is a solution with javascript only, without any jquery.

<html>
<head>
<script type="text/javascript">
function Validate() {
    var radios = document.getElementsByName('IDType')

    for (var i = 0; i < radios.length; i++) {
        if (radios[i].checked) {
        alert("Selected Value = " + radios[i].value);
        return true; // checked
    }
    };

    // not checked, show error
    document.getElementById('ValidationError').innerHTML = 'Error!!!';
    return false;
}
</script>
</head>
<body>
<form>
<div>
<span>
<input type="radio" name="IDType" value="IDtype1"/>
ID Type 1
<input type="radio" name="IDType" value="IDtype2"/>
ID Type 2
</span>
<div id="ValidationError" name="ValidationError">
</div>
</div>
<input type="submit" value="Submit" onclick="return Validate();" />
</form>
</body>
</html>

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

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