How to pass multiple checkbox values into an array

16,719

Solution 1

You need to have a change handler where you need to filter the checked checkbox elements

 var vals = [];
 $(document).ready(function () {

     var $checkes = $('input:checkbox[name="check[]"]').change(function () {
         vals = $checkes.filter(':checked').map(function () {
             return this.value;
         }).get();

         alert(JSON.stringify(vals));
     });
 });

Demo: Fiddle

Solution 2

You can do this using the .map() method like:

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

alert(vals[0]);

Fiddle Demo

Solution 3

your code is correct just put

var vals = [];

outside of

$(document).ready();

like

<script>
var vals = [];
$(document).ready(function(){
$('input:checkbox[name="check[]"]').each(function() {
    if (this.checked) {
        vals.push(this.value);
    }
});

 alert(vals[0]);
});
</script>
Share:
16,719
Hashey100
Author by

Hashey100

Updated on June 14, 2022

Comments

  • Hashey100
    Hashey100 almost 2 years

    I am trying to pass values from a checkbox list when selected to a jquery function, so i can play around with the selected values. Below the code does not work

    I want to be able to use the value outside of the checkbox function

    So for example if i had another button outside that function it should be able to read what was stored into the array - The code below does not work for some reason, any help would be appreciated

    jquery

     <script>
        $(document).ready(function(){
    
        var vals = []
        $('input:checkbox[name="check[]"]').each(function() {
            if (this.checked) {
                vals.push(this.value);
            }
        });
    
         alert(vals[0]);
        });
        </script>
    

    HTML Code

    <form>
    <input value="BOOZE" type="checkbox" name="check[]" >PUB, MATES, <br>
    <input value="TV"  type="checkbox" name="check[]">BRIBING THE KIDS TO GO BED<br>
    <input value="BOOZE" type="checkbox" name="check[]">RAVING TILL THE EARLY HOURS<br>
    <input value="PETS"  type="checkbox" name="check[]">PLAYING GRAND THEFT AUTO <br>
    <input value="GEEK"  type="checkbox" name="check[]">TWEETING ABOUT SOMETHING <br>
    <input value="SPORT"  type="checkbox" name="check[]">GYM<br>
    <input value="XMAS"  type="checkbox" name="check[]">SINGING CHRISTMAS SONGS<br>
    <input type="checkbox" class="chkNumber" name="check[]">SHARING A DELIGHTFUL BOTTLE 
    </form> 
    
  • Sohil Desai
    Sohil Desai over 10 years
    this is correct but here variable vals is not globel its scope is of $('input:checkbox[name="check[]"]').change(); function he can not use those values for another event or function