Getting all selected checkboxes in an array
Asked Answered
U

29

226

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

Urgent answered 26/2, 2009 at 10:45 Comment(2)
Possible duplicate of jquery multiple checkboxes arrayLorna
While the other question 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).Lorna
T
413

Formatted :

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

Hopefully, it will work.

Tolman answered 26/2, 2009 at 10:52 Comment(5)
and what to do if uncheck check box, to remove value from arrayUthrop
@JubinPatel you just need to reset the array before this code. yourArray = []Dowser
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()Hillinck
function get_selected_checkboxes_array(){ var ch_list=Array(); $("input:checkbox[type=checkbox]:checked").each(function(){ch_list.push($(this).val());}); return ch_list; }Bojorquez
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"}, ]Phlegm
C
141

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)
}
Conversational answered 2/9, 2017 at 16:18 Comment(3)
Always love a vanilla JS answer.Wame
yes some time we really don't want to use jQueryForfeiture
Also your solution with map function for vanilla JS. Array.from(document.querySelectorAll("input[name='type']:checked")).map((elem) => elem.value)Jugendstil
W
57
var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;             

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 
Weald answered 2/3, 2012 at 7:45 Comment(3)
As I understand the code above, it iterates through all the checkboxes and uncheck them. How this answer is connected with the question?Beforehand
This simply loops through the checkboxes and un-checks them. For the correct answer, in VanillaJS, please see the answer of zahid ullah below.Mopboard
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?Arrant
M
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>
Michey answered 26/2, 2009 at 10:55 Comment(1)
push to add value in array but what to remove on uncheck?Uthrop
O
41

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
Obey answered 2/10, 2019 at 10:44 Comment(4)
it should be ...map((i,e) => e.value)) actually...Dislike
@Dislike 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 developer.mozilla.org/nl/docs/Web/JavaScript/Reference/…Canst
Nice one line solution. Can be easily reused in a method with input name as parameter and a return statement to get the array.Maneuver
very nice, I think you should add const checked =Foreman
F
32

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>
Foch answered 25/8, 2017 at 6:56 Comment(0)
R
23

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');
Rarebit answered 26/2, 2009 at 10:53 Comment(1)
this does not answer the question on hoe to put the values into an arrayGlazed
B
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>
Beforehand answered 18/8, 2016 at 11:53 Comment(0)
S
14

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

var array = [];
$$("input[type=checkbox]:checked").each(function(i){
    array.push( i.value );
});
Spiros answered 26/6, 2011 at 12:45 Comment(3)
Didn't realise the age of the question or nature of solution was relevant.Spiros
Because I found this question when looking for the answer to the same problem using MooTools.Spiros
Note this answer relates to MooTools 1.3, not jQuery.Spiros
T
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;
}   
Tantara answered 10/5, 2015 at 6:1 Comment(0)
T
5
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
        return this.value;
    }).get();
Tulatulip answered 9/9, 2016 at 16:57 Comment(0)
D
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
Didactic answered 2/7, 2019 at 10:16 Comment(0)
O
3

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();
Outdated answered 11/5, 2017 at 2:53 Comment(0)
B
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>
Blasphemy answered 16/11, 2017 at 7:33 Comment(1)
Please add a bit of explanation to your answer. Pure code answers aren't usually useful.Theseus
E
3

Select Checkbox by input name

var category_id = [];

$.each($("input[name='yourClass[]']:checked"), function(){                    
    category_id.push($(this).val());
});
Edsel answered 4/3, 2021 at 9:5 Comment(0)
R
3
Array.from($(".yourclassname:checked"), a => a.value);
Rouse answered 17/3, 2022 at 11:43 Comment(1)
Your answer could be improved by adding more information on what the code does and how it helps the OP.Menides
S
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>
Sugar answered 16/3, 2016 at 10:9 Comment(0)
S
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;
}
Salesman answered 7/4, 2019 at 6:49 Comment(2)
For a useful answer this reaction needs to be extended. Explain why this is an answer to the question.Puparium
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 and adjust your answer accordingly. Thanks!Giltzow
E
1
var array = []
    $("input:checkbox[name=type]:checked").each(function(){
        array.push($(this).val());
    });
Exploration answered 4/5, 2020 at 20:16 Comment(0)
S
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");
Scyphozoan answered 5/5, 2021 at 15:14 Comment(0)
G
1

Use below code to get all checked values

        var yourArray=[];
        $("input[name='ordercheckbox']:checked").each(function(){
            yourArray.push($(this).val());
        });
        console.log(yourArray);
Gastight answered 25/7, 2022 at 2:32 Comment(0)
W
1
 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
   return this.value;
}).get();
Wavell answered 12/12, 2022 at 11:45 Comment(0)
G
1

Answer a bit similar to @enguerranws 's one:

$('.your-check-box-class:checked').toArray().map(x =>x.value);

assuming all the checkbox of said group are using the .your-check-box-class class.

Glazed answered 12/1 at 12:51 Comment(0)
L
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>
Leonleona answered 18/10, 2017 at 11:56 Comment(0)
S
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,
Stogner answered 13/4, 2018 at 10:6 Comment(0)
T
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>
Teak answered 4/5, 2018 at 9:56 Comment(0)
N
0
 var idsComenzi = [];

    $('input:checked').each(function(){
        idsComenzi.push($(this).val());
    });
Needlepoint answered 12/10, 2021 at 12:13 Comment(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: stackoverflow.com/help/how-to-answer . Good luck 🙂Davidoff
N
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.

Norvil answered 11/7, 2022 at 15:43 Comment(0)
R
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>
Revengeful answered 8/11, 2022 at 12:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.