How to get the checked option in a group of radio inputs with JavaScript?
views:
703answers:
4
+2
A:
<html>
<head>
<script type="text/javascript">
function testR(){
var x = document.getElementsByName('r')
for(var k=0;k<x.length;k++)
if(x[k].checked){
alert('Option selected: ' + x[k].value)
}
}
</script>
</head>
<body>
<form>
<input type="radio" id="r1" name="r" value="1">Yes</input>
<input type="radio" id="r2" name="r" value="2">No</input>
<input type="radio" id="r3" name="r" value="3">Don't Know</input>
<br/>
<input type="button" name="check" value="Test" onclick="testR()"/>
</form>
</body>
</html>
leoinfo
2008-10-02 13:58:19
But using document.all to get elements is a bad practice as it only works in a few browsers, use the standard document.getElementsByName instead !-)
roenving
2008-10-02 14:47:16
You're right... but I think Daniel got the idea.Anyway, I changed "document.all" to "document.getElementsByName"
leoinfo
2008-10-02 15:03:34
+2
A:
If you need the actual element and not just the selected value, try this:
function findSelected(){
for (i=0;i<document.formname.radioname.length;i++){
if (document.formname.radioname[i].checked){
return document.formname.radioname[i];
}
}
}
Wayne
2008-10-02 14:01:26
A:
generic functions (loosely based on yours )
function getRadioGroupSelectedElement(radioGroupName) {
var radioGroup = document.getElementsByName(radioGroupName);
var radioElement = radioGroup.length;
for(radioElement; radioElement >= 0; radioElement--) {
if(radioGroup[radioElement].checked){
return radioGroup[radioElement];
}
}
return false;
}
function getRadioGroupSelectedValue(radioGroupName) {
var selectedRadio = getRadioGroupSelectedElement(radioGroupName);
if (selectedRadio !== false) {
return selectedRadio.value;
}
return false;
}
Markus Albe
2009-02-26 19:07:23