user298519 user298519 - 6 months ago 12
Javascript Question

JQuery: Counter wrapped in an if statement not working?

So I have two of these select menus, and I want the counter to add 1 each time a right selection is selected in each selection. But it stays at 1.. How do I fix this?

HTML:

<div class="row"><!--first row-->

<div class="col-sm-3 col-xs-12 unit" >
<img src="img/shiny-apple.png" id="apple">
<p class="selectby">Fruit</p>
<select>
<option value="default"></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="grapes">grapes</option>
<option value="carrot">carrot</option>
</select>
</div><!-- end of col-->

<div class="col-sm-3 col-xs-12 unit" >
<img src="img/carrot.png" id="carrot">
<p class="selectby">Fruit</p>
<select>
<option value="default"></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="grapes">grapes</option>
<option value="carrot">carrot</option>
</select>
</div><!-- end of col-->


JS:

$("select").change(function() {

$selectedItem = $(this).val();
$imgId = $(this).siblings().attr('id');
var counter = 0;

// if the image ID string includes the selected option string
if ( $imgId.includes($selectedItem) ) {
$(this).parent().css("background-color", "lightgreen");
$(this).prop('disabled', true);

counter++;
console.log(counter);
}

});

Answer

var counter = 0;//put counter outside of change so it wont be initialize to 0 every change event
$("select").change(function() {

  $selectedItem = $(this).val();
  $imgId = $(this).siblings().attr('id');


  // if the image ID string includes the selected option string
  if ($imgId.includes($selectedItem)) {
    $(this).parent().css("background-color", "lightgreen");
    $(this).prop('disabled', true);

    counter++;
    console.log(counter);
  }
alert(counter)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <!--first row-->

  <div class="col-sm-3 col-xs-12 unit">
    <img src="img/shiny-apple.png" id="apple">
    <p class="selectby">Fruit</p>
    <select>
      <option value="default"></option>
      <option value="apple">apple</option>
      <option value="banana">banana</option>
      <option value="grapes">grapes</option>
      <option value="carrot">carrot</option>
    </select>
  </div>
  <!-- end of col-->

  <div class="col-sm-3 col-xs-12 unit">
    <img src="img/carrot.png" id="carrot">
    <p class="selectby">Fruit</p>
    <select>
      <option value="default"></option>
      <option value="apple">apple</option>
      <option value="banana">banana</option>
      <option value="grapes">grapes</option>
      <option value="carrot">carrot</option>
    </select>
  </div>
  <!-- end of col-->

place the counter outside the change event. Because every change event it is initialized to 0 again

Comments