Get selected checkbox value with jquery

1

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

$("input[type=checkbox]:checked").each(function(){
        //cada elemento seleccionado
        alert($(this).val());
    });

How could I store the values in variables separately?

    
asked by arglez35 01.08.2018 в 22:04
source

2 answers

0

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;
    }).get();
    
    var str = arr.join(',');
    
    $('#arr').text(JSON.stringify(arr));
    
    $('#str').text(str);
  
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></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>
  </ul>
  
  <div >Ids seleccionados en matriz <span id="arr"></span></div>
  <div >Ids seleccionados <span id="str"></span></div>
</div>
    
answered by 01.08.2018 / 22:13
source
2

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

let valoresCheck = [];

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

The values will be saved in the array.

EDITION :
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