210

So I have these checkboxes:

<input type="checkbox" name="type" value="4" />
<input type="checkbox" name="type" value="3" />
<input type="checkbox" name="type" value="1" />
<input type="checkbox" name="type" value="5" />

And so on. There are about 6 of them and are hand-coded (i.e not fetched from a db) so they are likely to remain the same for a while.

My question is how I can get them all in an array (in javascript), so I can use them while making an AJAX $.post request using Jquery.

Any thoughts?

Edit: I would only want the selected checkboxes to be added to the array

Ali
  • 249,782
  • 257
  • 562
  • 750
  • 1
    Possible duplicate of [jquery multiple checkboxes array](https://stackoverflow.com/questions/6166763/jquery-multiple-checkboxes-array) – Jason C Jul 17 '17 at 14:02
  • 1
    While the [other question](https://stackoverflow.com/questions/6166763/jquery-multiple-checkboxes-array) is newer and this one is more popular, the other one has a better, more succinct collection of answers (including the strategies here, plus some). – Jason C Jul 17 '17 at 14:02
  • This question does not have code that was attempted and yet still draws upvotes and answers, voting to close – Mark Schultheiss Oct 12 '21 at 12:38

24 Answers24

396

Formatted :

$("input:checkbox[name=type]:checked").each(function(){
    yourArray.push($(this).val());
});

Hopefully, it will work.

rrk
  • 15,214
  • 4
  • 26
  • 42
ybo
  • 16,679
  • 2
  • 27
  • 31
  • 2
    and what to do if uncheck check box, to remove value from array – Jubin Patel Jun 07 '13 at 10:38
  • @JubinPatel you just need to reset the array before this code. `yourArray = []` – rrk Jun 12 '15 at 05:47
  • 17
    You can also define your array immediately using `map` instead of `each`: `var yourArray = $("input:checkbox[name=type]:checked").map(function(){return $(this).val()}).get()` – Duvrai Dec 30 '15 at 16:19
  • 3
    `function get_selected_checkboxes_array(){ var ch_list=Array(); $("input:checkbox[type=checkbox]:checked").each(function(){ch_list.push($(this).val());}); return ch_list; }` – M at Mar 08 '17 at 22:23
98

Pure JS

For those who don't want to use jQuery

var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')

for (var i = 0; i < checkboxes.length; i++) {
  array.push(checkboxes[i].value)
}
Chris Underdown
  • 1,349
  • 10
  • 6
56
var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 
Tim Cooper
  • 151,519
  • 37
  • 317
  • 271
Milind
  • 665
  • 5
  • 2
  • 7
    As I understand the code above, it iterates through all the checkboxes and uncheck them. How this answer is connected with the question? – Terite Aug 18 '16 at 10:42
  • 2
    This simply loops through the checkboxes and un-checks them. For the correct answer, in VanillaJS, please see the answer of zahid ullah below. – jmknoll Aug 31 '16 at 16:13
  • 2
    How does this answer the question? This does something completely unrelated to what is asked. Why are there so many upvotes? Am I missing something, or was the question edited after people upvoted it? – Shubham Chaudhary Dec 15 '19 at 15:52
41

I didnt test it but it should work

<script type="text/javascript">
var selected = new Array();

$(document).ready(function() {

  $("input:checkbox[name=type]:checked").each(function() {
       selected.push($(this).val());
  });

});

</script>
Barbaros Alp
  • 6,283
  • 8
  • 46
  • 59
28

ES6 version:

const values = Array
  .from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);

function getCheckedValues() {
  return Array.from(document.querySelectorAll('input[type="checkbox"]'))
  .filter((checkbox) => checkbox.checked)
  .map((checkbox) => checkbox.value);
}

const resultEl = document.getElementById('result');

document.getElementById('showResult').addEventListener('click', () => {
  resultEl.innerHTML = getCheckedValues();
});
<input type="checkbox" name="type" value="1" />1
<input type="checkbox" name="type" value="2" />2
<input type="checkbox" name="type" value="3" />3
<input type="checkbox" name="type" value="4" />4
<input type="checkbox" name="type" value="5" />5

<br><br>
<button id="showResult">Show checked values</button>
<br><br>
<div id="result"></div>
quotesBro
  • 4,898
  • 2
  • 29
  • 40
26

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
Wilbert
  • 1,378
  • 12
  • 13
  • most concise solution using vanilla JS – M. Mufti Apr 10 '20 at 09:32
  • 1
    it should be `...map((i,e) => e.value))` actually... – spetsnaz Sep 29 '20 at 21:55
  • 2
    @spetsnaz index is the SECOND element, so if you need the index you need to do (e,i). Which of course is not necessary in this case. See https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/map – gabn88 Jan 13 '21 at 15:45
  • Nice one line solution. Can be easily reused in a method with input name as parameter and a return statement to get the array. – ronline Feb 28 '21 at 21:54
  • 1
    very nice, I think you should add `const checked =` – Tal Yaron Mar 27 '22 at 15:13
24

This should do the trick:

$('input:checked');

I don't think you've got other elements that can be checked, but if you do, you'd have to make it more specific:

$('input:checkbox:checked');

$('input:checkbox').filter(':checked');
Georg Schölly
  • 120,563
  • 48
  • 208
  • 262
14

If you want to use a vanilla JS, you can do it similarly to a @zahid-ullah, but avoiding a loop:

  var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
    return c.checked;
  }).map(function(c) {
    return c.value;
  });

The same code in ES6 looks a way better:

var values = [].filter.call(document.getElementsByName('fruits[]'), (c) => c.checked).map(c => c.value);

window.serialize = function serialize() {
  var values = [].filter.call(document.getElementsByName('fruits[]'), function(c) {
    return c.checked;
  }).map(function(c) {
    return c.value;
  });
  document.getElementById('serialized').innerText = JSON.stringify(values);
}
label {
  display: block;
}
<label>
  <input type="checkbox" name="fruits[]" value="banana">Banana
</label>
<label>
  <input type="checkbox" name="fruits[]" value="apple">Apple
</label>
<label>
  <input type="checkbox" name="fruits[]" value="peach">Peach
</label>
<label>
  <input type="checkbox" name="fruits[]" value="orange">Orange
</label>
<label>
  <input type="checkbox" name="fruits[]" value="strawberry">Strawberry
</label>
<button onclick="serialize()">Serialize
</button>
<div id="serialized">
</div>
Terite
  • 1,047
  • 13
  • 23
14

In MooTools 1.3 (latest at the time of writing):

var array = [];
$$("input[type=checkbox]:checked").each(function(i){
    array.push( i.value );
});
Lee Goddard
  • 9,582
  • 3
  • 45
  • 56
12

In Javascript it would be like this (Demo Link):

// get selected checkboxes
function getSelectedChbox(frm) {
  var selchbox = [];// array that will store the value of selected checkboxes
  // gets all the input tags in frm, and their number
  var inpfields = frm.getElementsByTagName('input');
  var nr_inpfields = inpfields.length;
  // traverse the inpfields elements, and adds the value of selected (checked) checkbox in selchbox
  for(var i=0; i<nr_inpfields; i++) {
    if(inpfields[i].type == 'checkbox' && inpfields[i].checked == true) selchbox.push(inpfields[i].value);
  }
  return selchbox;
}   
gvlasov
  • 16,604
  • 19
  • 65
  • 103
zahid ullah
  • 371
  • 3
  • 15
5
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
        return this.value;
    }).get();
Jean-Marc Amon
  • 919
  • 13
  • 15
3

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();
Pang
  • 9,073
  • 146
  • 84
  • 117
MHK
  • 31
  • 1
3

On checking add the value for checkbox and on dechecking subtract the value

$('#myDiv').change(function() {
  var values = 0.00;
  {
    $('#myDiv :checked').each(function() {
      //if(values.indexOf($(this).val()) === -1){
      values=values+parseFloat(($(this).val()));
      // }
    });
    console.log( parseFloat(values));
  }
});
<div id="myDiv">
  <input type="checkbox" name="type" value="4.00" />
  <input type="checkbox" name="type" value="3.75" />
  <input type="checkbox" name="type" value="1.25" />
  <input type="checkbox" name="type" value="5.50" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Joepraveen
  • 49
  • 4
3

Another way of doing this with vanilla JS in modern browsers (no IE support, and sadly no iOS Safari support at the time of writing) is with FormData.getAll():

var formdata   = new FormData(document.getElementById("myform"));
var allchecked = formdata.getAll("type"); // "type" is the input name in the question

// allchecked is ["1","3","4","5"]  -- if indeed all are checked
foz
  • 2,591
  • 1
  • 24
  • 19
2

Select Checkbox by input name

var category_id = [];

$.each($("input[name='yourClass[]']:checked"), function(){                    
    category_id.push($(this).val());
});
Nazmul Haque
  • 457
  • 5
  • 11
2
Array.from($(".yourclassname:checked"), a => a.value);
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Mar 20 '22 at 17:26
1

Using Jquery

You only need to add class to every input, i have add class "source" you can change it of course

<input class="source" type="checkbox" name="type" value="4" />
<input class="source" type="checkbox" name="type" value="3" />
<input class="source" type="checkbox" name="type" value="1" />
<input class="source" type="checkbox" name="type" value="5" />

<script type="text/javascript">
$(document).ready(function() {
    var selected_value = []; // initialize empty array 
    $(".source:checked").each(function(){
        selected_value.push($(this).val());
    });
    console.log(selected_value); //Press F12 to see all selected values
});
</script>
Ahmed Bermawy
  • 1,990
  • 3
  • 34
  • 40
1

function selectedValues(ele){
  var arr = [];
  for(var i = 0; i < ele.length; i++){
    if(ele[i].type == 'checkbox' && ele[i].checked){
      arr.push(ele[i].value);
    }
  }
  return arr;
}
kapil
  • 11
  • 3
  • For a useful answer this reaction needs to be extended. Explain why this is an answer to the question. – Jeroen Heier Apr 07 '19 at 06:55
  • Welcome to Stack Overflow and thanks for your contribution! It would be nice if you would read this guide [How to write a good answer](https://stackoverflow.com/help/how-to-answer) and adjust your answer accordingly. Thanks! – David Apr 07 '19 at 07:07
1
var array = []
    $("input:checkbox[name=type]:checked").each(function(){
        array.push($(this).val());
    });
Salione
  • 341
  • 2
  • 12
0

Use commented if block to prevent add values which has already in array if you use button click or something to run the insertion

$('#myDiv').change(function() {
  var values = [];
  {
    $('#myDiv :checked').each(function() {
      //if(values.indexOf($(this).val()) === -1){
      values.push($(this).val());
      // }
    });
    console.log(values);
  }
});
<div id="myDiv">
  <input type="checkbox" name="type" value="4" />
  <input type="checkbox" name="type" value="3" />
  <input type="checkbox" name="type" value="1" />
  <input type="checkbox" name="type" value="5" />
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Nisal Edu
  • 6,289
  • 4
  • 25
  • 33
0

You could try something like this:

$('input[type="checkbox"]').change(function(){
       var checkedValue = $('input:checkbox:checked').map(function(){
                return this.value;
            }).get();         
            alert(checkedValue);   //display selected checkbox value     
 })

Here

$('input[type="checkbox"]').change(function() call when any checkbox checked or unchecked, after this
$('input:checkbox:checked').map(function()  looping on all checkbox,
floatingpurr
  • 6,509
  • 7
  • 39
  • 88
0

here is my code for the same problem someone can also try this. jquery

<script>
$(document).ready(function(){`
$(".check11").change(function(){
var favorite1 = [];        
$.each($("input[name='check1']:checked"), function(){                    
favorite1.push($(this).val());
document.getElementById("countch1").innerHTML=favorite1;
});
});
});
</script>
0

can use this function that I created

function getCheckBoxArrayValue(nameInput){
    let valores = [];
    let checked = document.querySelectorAll('input[name="'+nameInput+'"]:checked');
    checked.forEach(input => {
        let valor = input?.defaultValue || input?.value;
        valores.push(valor);
    });
    return(valores);
}

to use it just call it that way

getCheckBoxArrayValue("type");
0
 var idsComenzi = [];

    $('input:checked').each(function(){
        idsComenzi.push($(this).val());
    });
btz
  • 7
  • 5
  • 1
    While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value. You can find more information on how to write good answers in the help center: https://stackoverflow.com/help/how-to-answer . Good luck – nima Oct 12 '21 at 14:09