Reputation: 5784
Please take a look at this code and let me know why I am not able to load the array?
$(':checkbox[name=items]').on('change', function() {
var arr = $(':checkbox[name=items]:checked').map(function() {
return this.id;
})
.get();
$("#p-tap").on("click", function(){
console.log(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input type="checkbox" name="items" value="Item_1" /> Lower Development Cost <br />
<input type="checkbox" name="items" value="Item_2" /> Higher Energy Production<br />
<input type="checkbox" name="items" value="Item_3" /> Further From Human Populations<br />
<input type="checkbox" name="items" value="Item_3" /> Smaller Construction Footprint<br />
</div>
<button id="p-tap"> Print</button>
Upvotes: 0
Views: 22
Reputation: 1634
var arr
is defined inside checkbox change closure
which made it a local variable instead of global scope
change your code to
var arr;
$(':checkbox[name=items]').on('change', function() {
arr = $(':checkbox[name=items]:checked').map(function() {
return this.id;
})
.get()});
var arr;
$(':checkbox[name=items]').on('change', function() {
arr = $(':checkbox[name=items]:checked').map(function() {
return this.value;
})
.get();
});
$("#p-tap").on("click", function() {
console.log(arr);
$('#result').text(arr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<input type="checkbox" name="items" value="Item_1" />Lower Development Cost
<br />
<input type="checkbox" name="items" value="Item_2" />Higher Energy Production
<br />
<input type="checkbox" name="items" value="Item_3" />Further From Human Populations
<br />
<input type="checkbox" name="items" value="Item_3" />Smaller Construction Footprint
<br />
</div>
<button id="p-tap">Print</button>
<br/>
Result:
<div id="result">
</div>
Upvotes: 1