Posted by tech on
June 21, 2009
|
(2 votes, average: 5.00 out of 5)
Loading ...
|
|
These two functions for getting and setting a radio button using Javascript regardless of how many radio buttons there are in the group is shorter and simpler than the functions I posted before. The functions below came from this site.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| // return the value of the radio button that is checked
// return an empty string if none are checked, or
// there are no radio buttons
function getCheckedValue(radioObj) {
if (!radioObj) return "";
var radioLength = radioObj.length;
if (radioLength == undefined) {
if (radioObj.checked) return radioObj.value;
else return "";
}
for (var i=0; i<radioLength; i++) {
if (radioObj[i].checked) {
radioObj[i].value;
break;
}
}
return "";
}
// set the radio button with the given value as being checked
// do nothing if there are no radio buttons
// if the given value does not exist, all the radio buttons
// are reset to unchecked
function setCheckedValue(radioObj, newValue) {
if (!radioObj) return;
var radioLength = radioObj.length;
if (radioLength == undefined) {
radioObj.checked = (radioObj.value == newValue.toString());
return;
}
for (var i=0; i<radioLength; i++) {
radioObj[i].checked = false;
if (radioObj[i].value == newValue.toString()) {
[i].checked = true;
}
}
} |
Found this post useful? Buy me a cup of coffee or help support the sponsors on the right.