Skip to content

Getting Checkbox Value in jQuery

  • by
getting-checkbox-values-in-jquery

In HTML Form, the dropdown, checkbox type fields have an array of value. In this post, we are going to see how to get the array of selected Checkbox Value in jQuery

In this example, we are using jQuery each() to get each checked value in an array. Then this array values will be shown using a Javascript alert box. This will be used to validate checkbox field.

Creating HTML Form with Checkboxes

This HTML shows a form containing a list of frs with checkbox field.

<form name="frmFruit" id="frmFruits" action="" method="post">
  <div id="lang-list">
    <div class="frm-label">List of Fruit Names:</div>
    <div>
      <input type="checkbox" name="fruit" id="fruit1" value="Apple" >
      Apple<br/>
      <input type="checkbox" name="fruit" id="fruit2" value="Apricot" >
      Apricot<br/>
      <input type="checkbox" name="fruit" id="fruit3" value="Banana" >
      Banana<br/>
      <input type="checkbox" name="fruit" id="fruit4" value="Cherry" >
      Cherry<br/>
      <input type="checkbox" name="fruit" id="fruit5" value="Coconut" >
      Coconut<br/>
    </div>
    <div>
      <input id="btnSubmit" type="button" value="Submit" />
    </div>
  </div>
</form>
Previously, we have seen an example to implement Update/Delete Multiple Rows using PHP

Getting Checked Values using jQuery

This jQuery script is used to get the checked value from the form checkbox field using jQuery each(). Using this jQuery function it runs a loop to get the checked value and put it into an array. Then the selected values with the count will be shown using an alert box.

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script language="javascript" type="text/javascript">
	$(document).ready(function () {
	$("#btnSubmit").click(function(){
	var selectedFruit = new Array();
	$('input[name="fruit"]:checked').each(function() {
		selectedFruit.push(this.value);
	});
	alert("Number of selected Fruits: "+selectedFruit.length+"\n"+"And, they are: "+selectedFruit);
	});
	});
</script>

Conclusion

Thus we have learned how to Getting Checkbox Values in jQuery. This article described the checkbox type fields have an array of value.

I hope this example helped to create your own code to manage PHP sessions and time.

Leave a Reply

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