Get selected checkbox value with jquery


I have a small function that runs through all the checkboxes and shows the value of those that have been selected.

        //cada elemento seleccionado

How could I store the values in variables separately?

asked by arglez35 01.08.2018 в 22:04

2 answers


You could use a combination of the map function to get these values in an array, or in a string, where each value would be separated by a comma.

I give you an example, I hope it helps you:

$(document).ready(function() {

  $('[name="checks[]"]').click(function() {
    var arr = $('[name="checks[]"]:checked').map(function(){
      return this.value;
    var str = arr.join(',');

<script src=""></script>
<div style="height: 200px">
  <ul style="list-style: none;">
    <li><input name="checks[]" type="checkbox" value="0" /></li>
    <li><input name="checks[]" type="checkbox" value="1" /></li>
    <li><input name="checks[]" type="checkbox" value="2" /></li>
    <li><input name="checks[]" type="checkbox" value="3" /></li>
    <li><input name="checks[]" type="checkbox" value="4" /></li>
    <li><input name="checks[]" type="checkbox" value="5" /></li>
    <li><input name="checks[]" type="checkbox" value="6" /></li>
  <div >Ids seleccionados en matriz <span id="arr"></span></div>
  <div >Ids seleccionados <span id="str"></span></div>
answered by 01.08.2018 / 22:13

You can create an array with the values of the checks, like this:

let valoresCheck = [];


The values will be saved in the array.

If you really need to create an independent variable for each of the inputs, you can do so by accessing the window object and dynamically creating the variables, (I do not recommend doing this, it's highly confusing and impractical)

$("input[type=checkbox]:checked").each(function(index, check ){
    window["valorInput"+index] = check.value;

This will create a succession of variables in the global scope called valueInputN going from 0 to the amount of inputs that there is. I hope it works for something.

answered by 01.08.2018 в 22:13