Learn how to get the values associated with HTML checkboxes with the help of JavaScript code.
finding the value of a checkbox, form check box values, getting values associated with form check boxes
Finding the value of a checkboxGo to Finding the value of a checkboxHTML & JavaScriptGo to HTML and JavaScript tips and tricksTips and tricksGo to web development Tips and tricksHomepage

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>
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. To get the associated value/s, we'll use the following code:

<SCRIPT LANGUAGE="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).


Check the results

What kind/s of music do you listen to?
Rock
Reggae
Pop
Rap
Metal


AddThis Social Bookmark Button


Page contents: JavaScript code employed to find the values associated with an HTML form check box.

Page URL: http://www.webdevelopersnotes.com/tips/html/ finding_the_value_of_a_checkbox.php3



Join Mailing List


Feedback/Questions




50+ web hosting FAQs

Search engine for your website

Free software from Google - The Google Pack Collection

Create your own search engine
Search WebDevelopersNotes.com