Suffii
Suffii

Reputation: 5784

Having issue on Loading/Removing Checkbox to Array

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

Answers (1)

ram hemasri
ram hemasri

Reputation: 1634

  1. Your var arr is defined inside checkbox change closure which made it a local variable instead of global scope
    1. Your checkbox closure is missing })
    2. Your array will always be empty strings as you didn't set value for id attribute to checkbox

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

Related Questions