[javascript] 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

This question is related to javascript jquery

The answer is


You need to add .toArray() to the end of your .map() function

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

Demo: http://jsfiddle.net/sZQtL/


var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

     var ids = [];

$('input[id="find-table"]:checked').each(function() {
   ids.push(this.value); 
});

This one worked for me!


here allows is class of checkboxes on pages and var allows collects them in an array and you can check for checked true in for loop then perform the desired operation individually. Here I have set custom validity. I think it will solve your problem.

  $(".allows").click(function(){
   var allows = document.getElementsByClassName('allows');
   var chkd   = 0;  
   for(var i=0;i<allows.length;i++)
   {
       if(allows[i].checked===true)
       {
           chkd = 1;
       }else
       {

       }
   }

   if(chkd===0)
   {
       $(".allows").prop("required",true);
       for(var i=0;i<allows.length;i++)
        {
        allows[i].setCustomValidity("Please select atleast one option");
        }

   }else
   {
       $(".allows").prop("required",false);
       for(var i=0;i<allows.length;i++)
        {
        allows[i].setCustomValidity("");
        }
   }

}); 

I refactored your code a bit and believe I came with the solution for which you were looking. Basically instead of setting searchIDs to be the result of the .map() I just pushed the values into an array.

$("#merge_button").click(function(event){
  event.preventDefault();

  var searchIDs = [];

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

  console.log(searchIDs);
});

I created a fiddle with the code running.


DEMO: http://jsfiddle.net/PBhHK/

$(document).ready(function(){

    var searchIDs = $('input:checked').map(function(){

      return $(this).val();

    });
    console.log(searchIDs.get());

});

Just call get() and you'll have your array as it is written in the specs: http://api.jquery.com/map/

$(':checkbox').map(function() {
      return this.id;
    }).get().join();

Needed the form elements named in the HTML as an array to be an array in the javascript object, as if the form was actually submitted.

If there is a form with multiple checkboxes such as:

<input name='breath[0]' type='checkbox' value='presence0'/>
<input name='breath[1]' type='checkbox' value='presence1'/>
<input name='breath[2]' type='checkbox' value='presence2'/>
<input name='serenity'  type='text' value='Is within the breath.'/>
...

The result is an object with:

data = {
   'breath':['presence0','presence1','presence2'],
   'serenity':'Is within the breath.'
}


var $form = $(this),
    data  = {};

$form.find("input").map(function()
{
    var $el  = $(this),
        name = $el.attr("name");

    if (/radio|checkbox/i.test($el.attr('type')) && !$el.prop('checked'))return;

    if(name.indexOf('[') > -1)
    {
        var name_ar = name.split(']').join('').split('['),
            name    = name_ar[0],
            index   = name_ar[1];

        data[name]  = data[name] || [];
        data[name][index] = $el.val();
    }
    else data[name] = $el.val();
});

And there are tons of answers here which helped improve my code, but they were either too complex or didn't do exactly want I wanted: Convert form data to JavaScript object with jQuery

Works but can be improved: only works on one-dimensional arrays and the resulting indexes may not be sequential. The length property of an array returns the next index number as the length of the array, not the actually length.

Hope this helped. Namaste!


Do not use "each". It is used for operations and changes in the same element. Use "map" to extract data from the element body and using it somewhere else.