PDA

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



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

sunfighter
Dec 17th, 2013, 04: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
<br>
<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(group[x].checked){
error_code++;
}
}
if (error_code == 0) alert("FAIL"); // I would put a message to check a box - this is for show
}
</script>

jmrker
Dec 17th, 2013, 04: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.