231

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

asked Feb 26, 2009 at 10:45
2
  • 1
    Possible duplicate of jquery multiple checkboxes array Commented Jul 17, 2017 at 14:02
  • 1
    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). Commented Jul 17, 2017 at 14:02

29 Answers 29

416

Formatted :

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

Hopefully, it will work.

rrk
15.9k4 gold badges32 silver badges49 bronze badges
answered Feb 26, 2009 at 10:52
Sign up to request clarification or add additional context in comments.

5 Comments

and what to do if uncheck check box, to remove value from array
@JubinPatel you just need to reset the array before this code. yourArray = []
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()
function get_selected_checkboxes_array(){ var ch_list=Array(); $("input:checkbox[type=checkbox]:checked").each(function(){ch_list.push($(this).val());}); return ch_list; }
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"}, ]
146

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)
}
answered Sep 2, 2017 at 16:18

3 Comments

Always love a vanilla JS answer.
yes some time we really don't want to use jQuery
Also your solution with map function for vanilla JS. Array.from(document.querySelectorAll("input[name='type']:checked")).map((elem) => elem.value)
57
var chk_arr = document.getElementsByName("chkRights[]");
var chklength = chk_arr.length; 
for(k=0;k< chklength;k++)
{
 chk_arr[k].checked = false;
} 
answered Mar 2, 2012 at 7:45

3 Comments

As I understand the code above, it iterates through all the checkboxes and uncheck them. How this answer is connected with the question?
This simply loops through the checkboxes and un-checks them. For the correct answer, in VanillaJS, please see the answer of zahid ullah below.
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?
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>
answered Feb 26, 2009 at 10:55

1 Comment

push to add value in array but what to remove on uncheck?
44

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);
answered Oct 2, 2019 at 10:44

4 Comments

it should be ...map((i,e) => e.value)) actually...
@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 developer.mozilla.org/nl/docs/Web/JavaScript/Reference/…
Nice one line solution. Can be easily reused in a method with input name as parameter and a return statement to get the array.
very nice, I think you should add const checked =
35

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>

answered Aug 25, 2017 at 6:56

1 Comment

Another possibility is const values = [...document.querySelectorAll('input[type="checkbox"][name="features"]:checked')].map((checkbox) => checkbox.value)
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');
answered Feb 26, 2009 at 10:53

1 Comment

this does not answer the question on hoe to put the values into an array
16

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>

answered Aug 18, 2016 at 11:53

Comments

15

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

var array = [];
$$("input[type=checkbox]:checked").each(function(i){
 array.push( i.value );
});
answered Jun 26, 2011 at 12:45

3 Comments

Didn't realise the age of the question or nature of solution was relevant.
Because I found this question when looking for the answer to the same problem using MooTools.
Note this answer relates to MooTools 1.3, not jQuery.
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
20.3k22 gold badges85 silver badges120 bronze badges
answered May 10, 2015 at 6:01

Comments

5
var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
 return this.value;
 }).get();
answered Sep 9, 2016 at 16:57

Comments

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
answered Jul 2, 2019 at 10:16

Comments

3

Use this:

var arr = $('input:checkbox:checked').map(function () {
 return this.value;
}).get();
Pang
10.2k146 gold badges87 silver badges126 bronze badges
answered May 11, 2017 at 2:53

Comments

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>

answered Nov 16, 2017 at 7:33

1 Comment

Please add a bit of explanation to your answer. Pure code answers aren't usually useful.
3

Select Checkbox by input name

var category_id = [];
$.each($("input[name='yourClass[]']:checked"), function(){ 
 category_id.push($(this).val());
});
answered Mar 4, 2021 at 9:05

Comments

3
Array.from($(".yourclassname:checked"), a => a.value);
answered Mar 17, 2022 at 11:43

1 Comment

Your answer could be improved by adding more information on what the code does and how it helps the OP.
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>
answered Mar 16, 2016 at 10:09

Comments

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;
}

answered Apr 7, 2019 at 6:49

2 Comments

For a useful answer this reaction needs to be extended. Explain why this is an answer to the question.
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!
1
var array = []
 $("input:checkbox[name=type]:checked").each(function(){
 array.push($(this).val());
 });
answered May 4, 2020 at 20:16

Comments

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");
answered May 5, 2021 at 15:14

Comments

1

Use below code to get all checked values

 var yourArray=[];
 $("input[name='ordercheckbox']:checked").each(function(){
 yourArray.push($(this).val());
 });
 console.log(yourArray);
answered Jul 25, 2022 at 2:32

Comments

1
 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
 return this.value;
}).get();
answered Dec 12, 2022 at 11:45

Comments

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.

answered Jan 12, 2024 at 12:51

Comments

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>

answered Oct 18, 2017 at 11:56

Comments

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
8,74911 gold badges58 silver badges116 bronze badges
answered Apr 13, 2018 at 10:06

Comments

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>
answered May 4, 2018 at 9:56

Comments

0
 var idsComenzi = [];
 $('input:checked').each(function(){
 idsComenzi.push($(this).val());
 });
answered Oct 12, 2021 at 12:13

1 Comment

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 🙂
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.

answered Jul 11, 2022 at 15:43

Comments

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>

answered Nov 8, 2022 at 12:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.