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" />
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.
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.
function displayVals() { var singleValues = $( "#single" ). val(); var multipleValues = $( "input[name='hobby']:checked" ). val() || []; $( "p" ). html( "<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.
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(); }); }); });
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With