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

This entry was posted in Code, JavaScript. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

2 Comments

  1. Posted October 2, 2008 at 9:23 pm | Permalink

    Thank you very much for this. This bug was driving me nuts this afternoon. I owe you a beer.

  2. Mike
    Posted December 15, 2008 at 9:25 am | Permalink

    Make that 2 beer coming up!!!

One Trackback

  1. [...] 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 [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*
  • Follow

  • Archives (since 2003)

  • Categories

  • Recent Posts

  • Twitter Updates

  • del.icio.us links

  • Flickr

    Runnymede Healthcare Centre Demolition : The EndRunnymede Healthcare Centre Demolition : The EndRunnymede Healthcare Centre Demolition : The EndRunnymede Healthcare Centre Demolition
  •  

    October 2007
    M T W T F S S
    « Sep   Nov »
    1234567
    891011121314
    15161718192021
    22232425262728
    293031  
  • Spam Blocked