Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Radiobutton Group Validation

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

like image 521
user614040 Avatar asked Mar 21 '26 04:03

user614040


1 Answers

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>
like image 139
vk_muse Avatar answered Mar 22 '26 17:03

vk_muse