Checkboxes are the best choice to collect multiple values. Normally, the selected checkbox values are posted on form submission to the server side. If you wish to get the checkbox valuses without form submission, then jQuery is the good option. Therefore with the help of jQuery command, we can easily retrieve the values of checkboxes.

Today, we will show you how to get the checkbox values using jQuery.

Using jQuery each(), you can get the values from the checkbox field. It will runs a loop to get the checked value and put it into an array.

For Example

<script type="text/javascript">
    $(document).ready(function() {
        $(".btn").click(function() {
            var colors = [];
            $.each($("input[name='color']:checked"), function() {
                colors.push($(this).val());
            });
            alert("My favourite colors are: " + colors.join(", "));
        });
    });
</script>

We will see the two examples script, one is getting values on the div wrapping a list of checkboxes and other one is based on the class of the checkbox. You can go with any one of the following with your comfortable one to integrate with your website.

Before that, you need to add the jQuery file to your web page.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript"></script>

Below is the jQuery function to get the value of checkboxes.

$(document).ready(function () {
	/* Get the checkboxes values based on the class attached to each check box */
	$("#buttonClass").click(function() {
	    getValueUsingClass();
	});
	
	/* Get the checkboxes values based on the parent div id */
	$("#buttonParent").click(function() {
	    getValueUsingParentTag();
	});
});

Leave a Reply

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