Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery multiple checkboxes array

<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!

like image 951
user557108 Avatar asked May 29 '11 08:05

user557108


People also ask

How can I get multiple checkboxes checked in jQuery?

Show activity on this post. for(var i = 0; i < values. length; i++) $("#list [value=" + values[i] + "]"). attr("checked", "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.

How can I get multiple checkbox values?

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.

How do I make an array of checkboxes in HTML?

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.


2 Answers

var checked = [] $("input[name='options[]']:checked").each(function () {     checked.push(parseInt($(this).val())); }); 
like image 94
Dormouse Avatar answered Nov 09 '22 18:11

Dormouse


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

like image 23
Russ Cam Avatar answered Nov 09 '22 19:11

Russ Cam