Javascript Radiobutton Group Validation

时间秒杀一切 提交于 2019-12-22 00:24:25

问题


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.....


回答1:


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

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>



回答2:


function validateRadioButtons(){ 
    var radio = $('input:radio[name="IDType"]:checked');
    if(radio.length == 0)//no buttons selected
       {
           $('ValidationError').text("you haven't selected any buttons!");
           return;
       }
    $('ValidationError').text(radio.val()+' is selected');
}

ps: in order for this to work, you should consider using unique id's for dom elements. you cannot have the same id ("IDType") for both your radio buttons.



来源:https://stackoverflow.com/questions/4977084/javascript-radiobutton-group-validation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!