JavaScript for a single element radio button list
Posted under JavaScript, Code, on Tuesday, October 16th, 2007;The Problem here is if your list of data generated radio button html yields only one value. All the standard solutions / samples that a google yields assume the there are 2 or more choices.
This is not unreasonable for radio buttons, but if your list of choices is not hand built then you may not have control over that.
Code is not reasonable and neither is Life.
And in that unreasonable use case those solutions fail, because if you have one one element in the radio button list then “f.choiceview.length = undefined” (assuming the html input tag name=”choiceview” ). Then the real fun begins…
How to fix this? The solution is simple if not obvious : the single element becomes a ordinary input tag type of element and you use the .checked and .value methods, as below….
function getSelected () {
var Selected = "";
var f = document.forms[0];
if(f.choiceview.checked) { // one element to fetch
Selected = f.view.value;
}
else {
for (var i = 0; i < f.choiceview.length; i ++) { //loop thur array
if (f.view[i].checked) { // test to see if checked
Selected = f.view[i].value;
}
}
}
if (Selected == "") {
alert("Nothing selected");
}
else {
alert(Selected + ' Selected'); // report back
}
}
Where would you use this? Mostly for form validation, or to grab user choices to drive other processing.
The same issue and solution applies to html CheckBox elements.
Update Oct 2008: I’ve revised the code and removed the hard coding of the html elements “name” attribute, and linked to a demo form of it action of radio buttons and check boxes. Plus, if your interested, I also rewrote the whole thing down to 1 line using the Prototype javascript framework! All here in JavaScript for a single element radio button list, revisited with Prototype
See also- JavaScript for a single element radio button list, revisited with Prototype
- Building a Better Drop Down Selection List for Ruby on Rails
- Using Javascript in a Lotus Notes Client app
- Programmable Fine Grain Control for Lotus Notes Document Deletion
- Tab interface for static content using JavaScript Prototype


October 2nd, 2008 at
[…] year I posted JavaScript for a single element radio button list, referring to a issue I had with get the value of generated radio button […]
October 2nd, 2008 at
Thank you very much for this. This bug was driving me nuts this afternoon. I owe you a beer.