<input type="checkbox" name="options[]" value="1" /> <input type="checkbox" name="options[]" value="2" /> <input type="checkbox" name="options[]" value="3" /> <input type="checkbox" name="options[]" value="4" /> <input type="checkbox" name="options[]" value="5" />
How I can make an array with values of checkboxes that are checked?
NOTE: (IMPORTANT) I need an array like [1, 2, 3, 4, 5] and not like ["1", "2", "3", "4", "5"] .
NOTE: There are around 50 checkboxes.
Can someone help me? Please!
Thank you!
Show activity on this post. for(var i = 0; i < values. length; i++) $("#list [value=" + values[i] + "]"). attr("checked", "checked");
function displayVals() { var singleValues = $( "#single" ). val(); var multipleValues = $( "input[name='hobby']:checked" ). val() || []; $( "p" ). html( "<b>Single:</b> " + singleValues + " <b>Multiple:</b> " + multipleValues.
To get an array of selected checkboxes values we need to use jQuery each() method and :checked selector on a group of checkboxes. The each() method will loop over the checkboxes group in which we can filter out selected checkboxes using :checked selector.
To link several checkboxes together to make them into an array in the PHP $_POST array you need to make all of the checkboxes have the same name, and each name must end in "[]". When both of the checkboxes are filled and the form is submitted this produces the following array.
var checked = [] $("input[name='options[]']:checked").each(function () { checked.push(parseInt($(this).val())); });
You can use $.map()
(or even the .map()
function that operates on a jQuery object) to get an array of checked values. The unary (+) operator will cast the string to a number
var arr = $.map($('input:checkbox:checked'), function(e,i) { return +e.value; }); console.log(arr);
Here's an example
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