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>
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With