JavaScript for a single element radio button list

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….

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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

5 Replies to “JavaScript for a single element radio button list”

  1. Pingback: False Positives » Blog Archive » JavaScript for a single element radio button list, revisited with Prototype

  2. not proper …….
    i didn’t got any useful result…….
    please help me out…..

    > krunal,
    > Sorry to hear you had a problem.
    > What version and type of Browser have you tested it in?
    > make sure you html radio element is correct.
    > Try using FireBug (in FireFox) to debug and step thur the executing javascript.
    > Most likely source of problem is typo’s in the html or the javascript.

Leave a Reply to Mike Cancel reply