Andrea Azzola

Tips and Techniques for Lifestyle Design

Get and Set Radio controls checked value with JavaScript

Posted on [Permalink]

Suppose you have the following radio controls:

   1:  <input name="Book" type="radio" value="asp" checked="true">ASP .NET</input><br />
   2:  <input name="Book" type="radio" value="wcf" >Windows Presentation Foundation</input><br />
   3:  <input name="Book" type="radio" value="slg" >Silverlight 2.0</input><br />


How do you get the selected value via JavaScript?
As you can see in the example, radio controls are declared in a particular way, there are no ids, instead there are names that identifies related radios.
You should be aware that Book is not treated as an unique control by the browser's engine, because each radio control correspond to one different element in the page.

The getElementsByName method
This method allows you to obtain a collection of controls from the (X)HTML DOM, by specifying the common name value.
Now we can write the following code to get or set the checked value:

 

 

   1:      function getRadio(name) {
   2:          var radios = document.getElementsByName(name);
   3:   
   4:          for (var i = 0; i < radios.length; i++) {
   5:              if (radios[i].checked) {
   6:                  return radios[i].value;
   7:              }
   8:          }
   9:   
  10:          return null;
  11:      }
  12:   
  13:      function setRadio(name, val) {
  14:          var radios = document.getElementsByName(name);
  15:   
  16:          for (var i = 0; i < radios.length; i++) {
  17:              radios[i].checked = (radios[i].value == val);
  18:          }
  19:      }

 

 

Categories:

Comments

Nice!

~Flavio