To Get Checkboxes Value With JQuery

A couple days ago I was working on my projects on web based application. One of the case is to create a form which has a lot of input type. One of them is checkbox. Unlike other input, checkbox needs a different way to get the values. If there is only one checkboxes group, it is so easy to get the value, but when it comes to many group of checkboxes, you will need different way to get the values.

If you create a form which only has a group of checkboxes, let’s say hobbies for example, you can use the script below to get the values.


var myVar='';
	   $(':checkbox:checked').each(function(){
			myVar+=$(this).val()+",";;
	   });

But if you have more than one group of checkboxes, you have to add id on each group. Take a look at form below:

On each checkbox group, you have to create class or id like the script below:

<input type="checkbox" value="1" id="interested" name="interested">Computer

To get the values, you can use the script below. In my case, I do not save the checkboxes value in an array, although you can use it to save the value. I save it in a variable and put “,” to separate each value.

 var hobby='';
	   $('#hobbies:checkbox:checked').each(function(){
			hobby+=$(this).val()+",";;
	   });
       var interest='';
       $('#interested:checkbox:checked').each(function(){
            interest=$(this).val();
       });

If you use the first jquery script to get the values of more than one group of checkboxes, then the value of all group will be saved on the same variable. This is why you need to add class on your html script.

Be Sociable, Share!

Related Posts:

Add a Comment

Your email address will not be published. Required fields are marked *