Getting all selected checkboxes in an array

Viewed 583256

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

27 Answers

Formatted :

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

Hopefully, it will work.

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>

Pure JavaScript with no need for temporary variables:

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

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

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

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>

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

Select Checkbox by input name

var category_id = [];

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

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

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

Use below code to get all checked values

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

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>

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>

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");
 var idsComenzi = [];

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

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.

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>

Related