Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass multiple checkbox values into an array

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> 
like image 605
Hashey100 Avatar asked Dec 25 '22 17:12

Hashey100


2 Answers

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

like image 177
Arun P Johny Avatar answered Dec 28 '22 09:12

Arun P Johny


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

like image 26
palaѕн Avatar answered Dec 28 '22 09:12

palaѕн