Finding the value of a checkbox

Finding the value of a checkbox cover image
  1. Home
  2. HTML
  3. Finding the value of a checkbox

Checkboxes allow you to receive multiple values. Like radio buttons, all checkboxes in a set have the same name but different values. However, unlike radio buttons, a visitor is free to choose one or more checkboxes.

Let’s see how we can extract the value of a checkbox.

<form name="orderform">
What kind/s of music do you listen to?<br>
<input type="checkbox" name="music" value="Rock"
checked="checked">Rock<br>
<input type="checkbox" name="music" value="Reggae">
Reggae<br>
<input type="checkbox" name="music" value="Pop">
Pop<br>
<input type="checkbox" name="music" value="Rap">
Rap<br>
<input type="checkbox" name="music" value="Metal">
Metal<br>
<input type="submit" onclick="get_check_value()">
</form>

orderform above contains a set of five checkboxes called music.

Sponsored Links

To get the associated value/s, we’ll use the following code:

<script type="text/javascript">
<!--

function get_check_value()
{
var c_value = "";
for (var i=0; i < document.orderform.music.length; i++)
   {
   if (document.orderform.music[i].checked)
      {
      c_value = c_value + document.orderform.music[i].value
      + "\n";
      }
   }
}

//-->
</script>

We first initialize a variable c_value that will hold the values of the selected checkboxes. document.orderform.music.length determines the number of checkboxes with the name music. In our case, we can substitute this with 5, since we already know the number. The for loop iterates through all the checkboxes in that set and determines which of these is checked using an If statement. Once a selected checkbox is found, its value is appended to the c_value variable.
This code should be placed inside the HTML Head section (unless you know what you are doing).

Click here to see how the code works

HTML JavaScript