jqueryjtogglebutton

How to increment counter and decrement it with Jquery


Hi guys I need assistance with incrementing a variable with just one value for a user and when the user clicks the same button the value decreases by one and this cycles continues. There is a situation similar in the below code:

$(function() {
  var indicator = 0;
  $('#btn1').on('click', function() {
    $('#toggleIndicator').show();
    indicator++;
    alert('ON value : ' + indicator);
  })

  $('#btn2').on('click', function() {
    $('#toggleIndicator').hide();
    indicator--;
    alert('OFF value : ' + indicator);
  })
});
div {
  width: 100px;
  height: 20px;
  margin-bottom: 10px;
}
.a {
  background-color: orange;
}
.b {
  background-color: gold;
}
.c {
  background-color: maroon;
}
.d {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="a" id="toggleIndicator">
</div>

<input type="button" id="btn1" value="ON" />
<input type="button" id="btn2" value="OFF" />

but in my case I want the actions to be on one button just like on or off. Any way to do this please?


Solution

  • HTML:

    <button id="btn">Click</button>
    

    jQuery:

    $(document).ready(function) {
       var state = true;
       var indicator = 0;
    
       $("#btn").click(function() {
         if(state) {
         indicator++;
         alert(indicator);
         state = false;
       } else {
         indicator--;
         alert(indicator);
         state = true;
       }
     });
    });
    

    Here's a fiddle: https://jsfiddle.net/qjm9dz2g/2/