jQuery get values of checked checkboxes into array

JavascriptJquery

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

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

Solution 3 - Javascript

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/

Solution 4 - Javascript

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.

Solution 5 - Javascript

     var ids = [];

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

This one worked for me!

Solution 6 - Javascript

var idsArr = [];

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

console.log(idsArr);

Solution 7 - Javascript

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: https://stackoverflow.com/questions/1184624/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!

Solution 8 - Javascript

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.

Solution 9 - Javascript

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionif __name__ is NoneView Question on Stackoverflow
Solution 1 - JavascriptAndrew WhitakerView Answer on Stackoverflow
Solution 2 - JavascriptCristi PufuView Answer on Stackoverflow
Solution 3 - JavascripttymeJVView Answer on Stackoverflow
Solution 4 - JavascriptMark MeyerView Answer on Stackoverflow
Solution 5 - JavascriptThalinda BandaraView Answer on Stackoverflow
Solution 6 - JavascriptQammar FerozView Answer on Stackoverflow
Solution 7 - Javascripti_aView Answer on Stackoverflow
Solution 8 - JavascriptMItrajyoti KusariView Answer on Stackoverflow
Solution 9 - JavascriptManishView Answer on Stackoverflow