Forum Moderators: open
If I remember correctly, let's say we have a group of 4 radio button as follow:
<input type="radio" name="group1" value="1" />
<input type="radio" name="group1" value="2" />
<input type="radio" name="group1" value="3" />
<input type="radio" name="group1" value="4" />
Now if you want to access the value of group1:
document.form.group1.value
So you can simply test with that value if the field you want is selected.
You might want to make sure one of those is selected by default to avoid uninitialized variables in case no selection is made by the user.
<html>
<head>
<title>Untitled</title>
<script type="text/javascript">
function check(){
for (i=0;i<document.form.group1.length;i++){
if(document.form.group1[i].checked){
alert(document.form.group1[i].value);
}
}
}</script>
</head>
<body>
<form name="form" action="">
<input type="radio" name="group1" value="1" />
<input type="radio" name="group1" value="2" />
<input type="radio" name="group1" value="3" />
<input type="radio" name="group1" value="4" />
<button onclick="check();">Click!</button>
</form>
</body>
</html>
That'll do it in one statement :), although I think that if you give each button a value, it might go through the array twice, once as a numerical array and once as an associative array -- but I could be wrong. This approach has the advantage that you don't need to hard-code how many elements there are (ease of maintenance, i.e. if at a later date you want to add or remove options).
Another approach cuts down the number of times to loop iterates, but the saving is probably minimal:
for(button in document.form.group1) if(document.form.group1[button].checked){
whereChecked=document.form.group1[button].value;
break;
}
An alternative:
for(i=0; i<document.form.group1.length; i++) if(document.form.group1[i].checked){
whereChecked=document.form.group1[i].value;
break;
}