224

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
  • 261,656
  • 265
  • 575
  • 769
  • 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

30 Answers30

410

Formatted :

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

Hopefully, it will work.

rrk
  • 15,677
  • 4
  • 29
  • 45
ybo
  • 16,967
  • 2
  • 28
  • 31
  • 2
    and what to do if uncheck check box, to remove value from array – Jubin Patel Jun 07 '13 at 10:38
  • 1
    @JubinPatel you just need to reset the array before this code. `yourArray = []` – rrk Jun 12 '15 at 05:47
  • 18
    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
  • Okay Hear me out. what if the checkbox has multiple data Attribute and each attribute need to be added in the array Like: Array checkbox[ {name:"name", price:"100", shipping:"10", discount:"10"}, {name:"name", price:"100", shipping:"10", discount:"10"}, {name:"name", price:"100", shipping:"10", discount:"10"}, {name:"name", price:"100", shipping:"10", discount:"10"}, ] – sam kh Oct 12 '22 at 04:26
134

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,719
  • 1
  • 12
  • 6
57
var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 
Milind
  • 675
  • 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
46

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,405
  • 8
  • 47
  • 61
37

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
Vincent Tallon
  • 163
  • 1
  • 5
Wilbert
  • 1,618
  • 15
  • 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
31

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
  • 6,030
  • 2
  • 31
  • 41
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
  • 124,188
  • 49
  • 220
  • 267
15

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,097
  • 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
  • 10,680
  • 4
  • 46
  • 63
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
  • 18,638
  • 21
  • 74
  • 110
zahid ullah
  • 371
  • 3
  • 15
5
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
        return this.value;
    }).get();
Jean-Marc Amon
  • 969
  • 13
  • 16
4

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
  • 3,121
  • 1
  • 27
  • 21
3

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();
Pang
  • 9,564
  • 146
  • 81
  • 122
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
Array.from($(".yourclassname:checked"), a => a.value);
  • 2
    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
2

Select Checkbox by input name

var category_id = [];

$.each($("input[name='yourClass[]']:checked"), function(){                    
    category_id.push($(this).val());
});
Nazmul Haque
  • 720
  • 8
  • 13
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
  • 2,290
  • 4
  • 35
  • 42
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());
    });
Sully
  • 392
  • 4
  • 14
1

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");
1

Use below code to get all checked values

        var yourArray=[];
        $("input[name='ordercheckbox']:checked").each(function(){
            yourArray.push($(this).val());
        });
        console.log(yourArray);
Pawan Verma
  • 1,152
  • 14
  • 22
1

This is an old question but in 2022 There is a better way to implement it using vanilla JS

We don't need react or fancy frameworks.

We just need handle two onchange events like this:

const types = [{id:1, name:'1'}, {id:2, name:'2'}, {id:3, name:'3'}, {id:4, name:'4'}, {id:5, name:'5'}, {id:6, name:'6'}]

const all = document.getElementById('select-all')
const summary = document.querySelector('p')

let selected = new Set()

const onCheck = event => {
  event.target.checked ? selected.add(event.target.value) : selected.delete(event.target.value)
  summary.textContent = `[${[...selected].join(', ')} | size: ${selected.size}] types selected.`
  all.checked = selected.size === types.length
}

const createCBInput = t => {
  const ol = document.querySelector('ol')
  const li = document.createElement('li')
  const input = document.createElement('input')
  input.type = 'checkbox'
  input.id = t.id
  input.name = 'type'
  input.value = t.id
  input.checked = selected.has(t.id)
  input.onchange = onCheck
  const label = document.createElement('label')
  label.htmlFor = t.id
  label.textContent = t.name

  li.append(input, label)
  ol.appendChild(li)
}

const onSelectAll = event => {
  const checked = event.target.checked
  for (const t of types) {
    const cb = document.getElementById(t.id)
    cb.checked = checked ? true : selected.has(t.id)
    const event = new Event('change')
    cb.dispatchEvent(event)
  }
}

all.checked = selected.size === types.length
all.onchange = onSelectAll

for (const t of types) {
  createCBInput(t)
}
ol {
  list-style-type: none;
  padding-left: 0;
}
<ol>
  <li>
    <input type="checkbox" id="select-all">
    <label for="select-all"><strong>Select all</strong></label>
  </li>
</ol>

<p></p>
Teocci
  • 7,189
  • 1
  • 50
  • 48
1
 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
   return this.value;
}).get();
dazzafact
  • 2,570
  • 3
  • 30
  • 49
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
  • 7,237
  • 4
  • 28
  • 34
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
  • 7,749
  • 9
  • 46
  • 106
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
 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
0

Just adding my two cents, in case it helps someone :

const data = $checkboxes.filter(':checked').toArray().map((item) => item.value);

I already had a jQuery object, so I wouldn't select all my checkbox another time, that's why I used jQuery's filter method. Then I convert it to a JS array, and I map the array to return items'value.

enguerranws
  • 8,087
  • 8
  • 49
  • 97
0

$(document).ready(function()
{
 $('input[type="checkbox"]').click(function() {
    var arr =[];
    $('input[type="checkbox"]:checked').each(function() {
     //arr.push($(this).parent('p').text()+'\n');
     arr.push($(this).val()+'\n');
    });
    var array = arr.toString().split(',')
    $("#text").val(array.join(""));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<p>Append value when checkbox is checked</p>
<textarea rows="4" id="text" style="width: 100%">
</textarea>


<div id="checkboxes">
  <p><input type="checkbox" value="Item 1"><span>&nbsp;&nbsp; Item 1</span></p>
  <p><input type="checkbox" value="Item 2"><span>&nbsp;&nbsp; Item 2</span></p>
  <p><input type="checkbox" value="Item 3"><span>&nbsp;&nbsp; Item 3</span></p>
  <p><input type="checkbox" value="Item 4"><span>&nbsp;&nbsp; Item 4</span></p>
  <p><input type="checkbox" value="Item 5"><span>&nbsp;&nbsp; Item 5</span></p>
</div>
0

I used this method and it is working perfectly, it will give you only the element which is checked

let data = document.querySelector('input[name="data"]:checked').value;