Getting all selected checkboxes in an array

JavascriptJqueryAjaxDhtml

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Formatted :

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

Hopefully, it will work.

Solution 2 - Javascript

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

Solution 3 - Javascript

var chk_arr =  document.getElementsByName("chkRights[]");
var chklength = chk_arr.length;				

for(k=0;k< chklength;k++)
{
    chk_arr[k].checked = false;
} 

Solution 4 - Javascript

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>

Solution 5 - Javascript

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>

Solution 6 - Javascript

Pure JavaScript with no need for temporary variables:

Array.from(document.querySelectorAll("input[type=checkbox][name=type]:checked"), e => e.value);

Solution 7 - Javascript

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

Solution 8 - Javascript

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

var array = [];
$$("input[type=checkbox]:checked").each(function(i){
    array.push( i.value );
});

Solution 9 - Javascript

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>

Solution 10 - Javascript

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

Solution 11 - Javascript

var checkedValues = $('input:checkbox.vdrSelected:checked').map(function () {
        return this.value;
    }).get();

Solution 12 - Javascript

Use this:

var arr = $('input:checkbox:checked').map(function () {
  return this.value;
}).get();

Solution 13 - Javascript

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>

Solution 14 - Javascript

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

Solution 15 - Javascript

Select Checkbox by input name

var category_id = [];

$.each($("input[name='yourClass[]']:checked"), function(){                    
    category_id.push($(this).val());
});

Solution 16 - Javascript

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>

Solution 17 - Javascript

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

Solution 18 - Javascript

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

Solution 19 - Javascript

Array.from($(".yourclassname:checked"), a => a.value);

Solution 20 - Javascript

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>

Solution 21 - Javascript

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,

Solution 22 - Javascript

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>

Solution 23 - Javascript

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

Solution 24 - Javascript

 var idsComenzi = [];

    $('input:checked').each(function(){
        idsComenzi.push($(this).val());
    });

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
QuestionAliView Question on Stackoverflow
Solution 1 - JavascriptyboView Answer on Stackoverflow
Solution 2 - JavascriptChris UnderdownView Answer on Stackoverflow
Solution 3 - JavascriptMilindView Answer on Stackoverflow
Solution 4 - JavascriptBarbaros AlpView Answer on Stackoverflow
Solution 5 - JavascriptquotesBroView Answer on Stackoverflow
Solution 6 - JavascriptWilbertView Answer on Stackoverflow
Solution 7 - JavascriptGeorg SchöllyView Answer on Stackoverflow
Solution 8 - JavascriptLee GoddardView Answer on Stackoverflow
Solution 9 - JavascriptTeriteView Answer on Stackoverflow
Solution 10 - Javascriptzahid ullahView Answer on Stackoverflow
Solution 11 - JavascriptJean-Marc AmonView Answer on Stackoverflow
Solution 12 - JavascriptMHKView Answer on Stackoverflow
Solution 13 - JavascriptJoepraveenView Answer on Stackoverflow
Solution 14 - JavascriptfozView Answer on Stackoverflow
Solution 15 - JavascriptNazmul HaqueView Answer on Stackoverflow
Solution 16 - JavascriptAhmed BermawyView Answer on Stackoverflow
Solution 17 - JavascriptkapilView Answer on Stackoverflow
Solution 18 - JavascriptSalioneView Answer on Stackoverflow
Solution 19 - JavascriptMuhammad ShazarView Answer on Stackoverflow
Solution 20 - JavascriptNisal EduView Answer on Stackoverflow
Solution 21 - Javascriptpappu kr SharmaView Answer on Stackoverflow
Solution 22 - JavascriptRahul GuptaView Answer on Stackoverflow
Solution 23 - JavascriptRubens FlincoView Answer on Stackoverflow
Solution 24 - JavascriptbtzView Answer on Stackoverflow