Jan Netherdrake Jan Netherdrake - 2 months ago 8
Javascript Question

jQuery get values of checked checkboxes into array

I am trying to get values of all checkboxes that are currently checked and store them into an array. Here is my code so far:

$("#merge_button").click(function(event){
event.preventDefault();
var searchIDs = $("#find-table input:checkbox:checked").map(function(){
return $(this).val();
});
console.log(searchIDs);
});


However this outputs more than I need. I not only get the values, but some other stuff I don't want.


["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003",
"51729975c9f267f3b5000002", prevObject: jQuery.fn.jQuery.init[3],
context: document, jquery: "1.9.1", constructor: function, init:
function…]


I would like just ID's (first 3 items in this case).

By using
$.each
and pushing values to an array I get desired output:

$("#find-table input:checkbox:checked").each(function(){ myArray.push($(this).val()); })



["51729b62c9f2673e4c000004", "517299e7c9f26782a7000003",
"51729975c9f267f3b5000002"]


However I'd like to use
$.map
, since it saves me a line of code and is prettier.

Thanks

Answer

Call .get() at the very end to turn the resulting jQuery object into a true array.

$("#merge_button").click(function(event){
    event.preventDefault();
    var searchIDs = $("#find-table input:checkbox:checked").map(function(){
      return $(this).val();
    }).get(); // <----
    console.log(searchIDs);
});

Per the documentation:

As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array.