Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get multiple checkbox values using jQuery?

Tags:

jquery

How can I get the values of checkboxes which are selected using jQuery?

My HTML code is as follows:

<input  id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" /> <input  id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" /> <input  id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" /> <input  id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" /> <input type="button" id="save_value" name="save_value" value="Save" /> 
like image 675
user 007 Avatar asked Aug 14 '12 04:08

user 007


People also ask

How can I get multiple checkbox values in jQuery?

Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.

How do I get multiple checkbox values?

Read Multiple Values from Selected CheckboxesUse the foreach() loop to iterate over every selected value of checkboxes and print on the user screen. <? php if(isset($_POST['submit'])){ if(! empty($_POST['checkArr'])){ foreach($_POST['checkArr'] as $checked){ echo $checked.

How do I store multiple checkbox values in an array?

function displayVals() { var singleValues = $( "#single" ). val(); var multipleValues = $( "input[name='hobby']:checked" ). val() || []; $( "p" ). html( "<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.


2 Answers

Try this

<input name="selector[]" id="ad_Checkbox1" class="ads_Checkbox" type="checkbox" value="1" /> <input name="selector[]" id="ad_Checkbox2" class="ads_Checkbox" type="checkbox" value="2" /> <input name="selector[]" id="ad_Checkbox3" class="ads_Checkbox" type="checkbox" value="3" /> <input name="selector[]" id="ad_Checkbox4" class="ads_Checkbox" type="checkbox" value="4" /> <input type="button" id="save_value" name="save_value" value="Save" /> 

function

    $(function(){       $('#save_value').click(function(){         var val = [];         $(':checkbox:checked').each(function(i){           val[i] = $(this).val();         });       });     }); 
like image 81
Juice Avatar answered Sep 16 '22 14:09

Juice


To get an array of values from multiple checked checkboxes, use jQuery map/get functions:

$('input[type=checkbox]:checked').map(function(_, el) {     return $(el).val(); }).get(); 

This will return array with checked values, like this one: ['1', '2']

Here is working example on jsfiddle: http://jsfiddle.net/7PV2e/

like image 20
dugokontov Avatar answered Sep 18 '22 14:09

dugokontov