views:

103

answers:

3

I know I can get the "value" attribute of a radiobutton but I'm finding it strangely difficult to get the text of the radiobutton.

Consider the example below. It has 3 radiobuttons and tries to alert the value of the first radio button, which is "red" and then trys to alert the value of the radiobutton, "apple" but that fails.

Getting the text of almost any element can be done with elem.childNodes[0].nodeValue. Why doesn't it work for radiobuttons?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >
<head>
<title>Radio Buttons</title>
<style type="text/css">
</style>
<script type="text/javascript">
function start(){
  var rblist = document.getElementsByName("colors");
  var elem = rblist[0];
  alert(elem.value); // PRINTS "RED"
  alert(elem.childNodes[0].nodeValue); //THROWS ERROR
}
</script>    
</head>
<body onload="start();">
<input type="radio" name="colors" value="red" checked>apple</input>
<input type="radio" name="colors" value="blue">sky</input>
<input type="radio" name="colors" value="green">grass</input>
</body>  
</html>
+7  A: 

It doesn't work because there is no such thing as text inside an <input> like that -- that's illegal in XHTML. It must be:

<input type="radio" name="colors" value="red" id="radio1" checked="checked" /><label for="radio1">apple</label>

Then you can look for the text inside the <label>.

Josh Leitzel
+1 - 2nd time I've seen someone put text in an `<input>` element today, interesting
John Rasch
+1 - I admit I didn't even know it was possible. ;) First time I saw something like this. Nevertheless the value can be retrieved, anyway (see my answer).
Pawel Krakowiak
A: 
elem.nextSibling.nodeValue.replace('\n', '')

The replace is to get rid of the newline (may be different on different OSes, I am running Windows) character which is there for some reason.

Pawel Krakowiak
A: 

This will work:

alert(elem.nextSibling.data);
Matthew Talbert