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!
Solution 1:
var checked = []
$("input[name='options[]']:checked").each(function ()
{
checked.push(parseInt($(this).val()));
});
Solution 2:
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
Solution 3:
var checkedString = $('input:checkbox:checked.name').map(function() { return this.value; }).get().join();