if __name__ is None
if __name__ is None

Reputation: 11533

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

Upvotes: 153

Views: 311390

Answers (9)

Manish
Manish

Reputation: 29

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("");
        }
   }

}); 

Upvotes: 0

Qammar Feroz
Qammar Feroz

Reputation: 718

var idsArr = [];

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

console.log(idsArr);

Upvotes: 4

Thalinda Bandara
Thalinda Bandara

Reputation: 1079

     var ids = [];

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

This one worked for me!

Upvotes: 11

i_a
i_a

Reputation: 2763

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!

Upvotes: 1

MItrajyoti
MItrajyoti

Reputation: 578

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.

Upvotes: 0

Cristi Pufu
Cristi Pufu

Reputation: 9095

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();

Upvotes: 26

Mark Meyer
Mark Meyer

Reputation: 3733

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.

Upvotes: 10

Andrew Whitaker
Andrew Whitaker

Reputation: 126082

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.

Upvotes: 320

tymeJV
tymeJV

Reputation: 104795

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/

Upvotes: 18

Related Questions