View Full Version : How to validate radio buttons in javascript?

Dec 17th, 2013, 12:51 PM
How to validate radio buttons in javascript are specific rules used

Dec 17th, 2013, 03:10 PM
Not sure what you mean by specific rules. JS allows some leeway in programing styles.
This is how I would do it.

Enter Your Gender<br>
<input type="radio" name="gender" value="male">Male
<input type="radio" name="gender" value="female">Female
<input type="button" onclick="test();" value="Submit" />

<script type="text/JavaScript">
function test(){
var error_code = 0;
var group = document.getElementsByName("gender");
for(var x=0; x < group.length; x++){
if (error_code == 0) alert("FAIL"); // I would put a message to check a box - this is for show

Dec 17th, 2013, 03:20 PM
Similar to last post, but a bit more generic and gives an alternative return value:

function getRBtnName(GrpName) {
var sel = document.getElementsByName(GrpName);
var fnd = -1;
var str = '';
for (var i=0; i<sel.length; i++) {
if (sel[i].checked) { str = sel[i].value; fnd = i; }
// return fnd; // return option index of selection
// comment out next line if option index used in line above
return str;

Pass the name of the radio group in the function.
Returns either the value of the selected radio option
or alternatively with the minor change, the selected index.