0

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>

1 Answer 1

1
  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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.