Ali
Ali

Reputation: 267077

Getting all selected checkboxes in an array

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

Upvotes: 230

Views: 669478

Answers (29)

sergiol
sergiol

Reputation: 4335

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.

Upvotes: 1

dazzafact
dazzafact

Reputation: 2860

 var checked= $('input[name="nameOfCheckbox"]:checked').map(function() {
   return this.value;
}).get();

Upvotes: 1

VENKATESH KARNI
VENKATESH KARNI

Reputation: 66

$(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>

Upvotes: 0

Pawan Verma
Pawan Verma

Reputation: 1269

Use below code to get all checked values

        var yourArray=[];
        $("input[name='ordercheckbox']:checked").each(function(){
            yourArray.push($(this).val());
        });
        console.log(yourArray);

Upvotes: 1

enguerranws
enguerranws

Reputation: 8233

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.

Upvotes: 0

Muhammad Shazar
Muhammad Shazar

Reputation: 79

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

Upvotes: 3

Wilbert
Wilbert

Reputation: 1818

Pure JavaScript with no need for temporary variables:

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

Upvotes: 44

btz
btz

Reputation: 7

 var idsComenzi = [];

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

Upvotes: 0

Rubens Flinco
Rubens Flinco

Reputation: 19

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

Upvotes: 1

Nazmul Haque
Nazmul Haque

Reputation: 868

Select Checkbox by input name

var category_id = [];

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

Upvotes: 3

Sully
Sully

Reputation: 417

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

Upvotes: 1

foz
foz

Reputation: 3379

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

Upvotes: 4

Misha
Misha

Reputation: 6588

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>

Upvotes: 35

kapil
kapil

Reputation: 11

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

Upvotes: 1

Joepraveen
Joepraveen

Reputation: 49

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>

Upvotes: 3

Rahul Gupta
Rahul Gupta

Reputation: 23

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>

Upvotes: 0

pappu kr Sharma
pappu kr Sharma

Reputation: 1

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,

Upvotes: 0

Barbaros Alp
Barbaros Alp

Reputation: 6434

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>

Upvotes: 46

Nisal Edu
Nisal Edu

Reputation: 7591

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>

Upvotes: 0

Chris Underdown
Chris Underdown

Reputation: 1829

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

Upvotes: 145

MHK
MHK

Reputation: 31

Use this:

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

Upvotes: 3

Jean-Marc Amon
Jean-Marc Amon

Reputation: 989

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

Upvotes: 5

Terite
Terite

Reputation: 1167

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>

Upvotes: 16

Ahmed Bermawy
Ahmed Bermawy

Reputation: 2530

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>

Upvotes: 1

ybo
ybo

Reputation: 17152

Formatted :

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

Hopefully, it will work.

Upvotes: 415

zahid ullah
zahid ullah

Reputation: 371

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

Upvotes: 12

Milind
Milind

Reputation: 675

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

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

Upvotes: 57

Lee Goddard
Lee Goddard

Reputation: 11173

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

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

Upvotes: 14

Georg Sch&#246;lly
Georg Sch&#246;lly

Reputation: 126105

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

Upvotes: 23

Related Questions