How to Interpret Radio Buttons in JavaScript for HTML5 and CSS3 Programming - dummies

How to Interpret Radio Buttons in JavaScript for HTML5 and CSS3 Programming

By Andy Harris

Getting information from a group of radio buttons in JavaScript requires a slightly different technique for your HTML5 page than most of the form elements. Unlike the select object, there is no container object that can return a simple value. You also can’t just go through every radio button on the page because you may have more than one group. (Imagine a page with a multiple-choice test.)

This issue is where the attribute comes in. Although ids must be unique, multiple elements on a page can have the same name. If they do, you can treat these elements as an array.

Look over the code to see how it works:

  // from radioGroup.html
  function fight(){
  var weapon = document.getElementsByName("weapon");
  for (i = 0; i < weapon.length; i++){
   currentWeapon = weapon[i];
   if (currentWeapon.checked){
   var selectedWeapon = currentWeapon.value;
   } // end if
  } // end for
  var output = document.getElementById("output");
  var response = "<h2>You defeated the dragon with a ";
  response += selectedWeapon + "</h2> n";
  output.innerHTML = response;
  } // end function

This code has a sneaky difference:

  • It uses getElementsByName to retrieve an array of elements with this name. Note that it’s plural because this tool is used to extract an array of elements. It returns an array of elements. (In this case, all the radio buttons in the group.)

  • It treats the result as an array. The resulting variable is an array. As usual, the most common thing to do with arrays is process them with loops. Use a for loop to step through each element in the array.

  • Assign each element of the array to currentWeapon. This variable holds a reference to the current radio button.

  • Check to see whether the current weapon is checked. The checked property indicates whether any radio button is checked.

  • If so, retain the value of the radio button. If a radio button is checked, its value is the current value of the group, so store it in a variable for later use.

  • Output the results. You can now process the results as you would with data from any other resource.