Home How to decrement a counter if a button is clicked the second time
Reply: 0

How to decrement a counter if a button is clicked the second time

user8941
1#
user8941 Published in September 20, 2018, 4:34 pm

I have the following code,each time a button is clicked it adds it to a counter as shown bellow, what i am trying to achieve is that if the same button is clicked the second time it must decrement the counter, currently if i press a single button multiple times it adds to a counter,i only want it to add to a counter when its clicked on the first time,the second time its clicked it must decrement the counter,i am trying to click each button only once and if its clicked on the second time it must decrement the counter

var counter = 0;

function count() {
  $('#notify').addClass("notification");
  $("#notify").html(counter);
}



$('body').on('click', '.btn', function(e) {
  counter++;
  count();
});
.notification {
  position: absolute;
  display: block;
  text-align: center;
  font-size: 9px;
  font-weight: 700;
  letter-spacing: -1px;
  width: auto;
  min-width: 8px;
  height: 9px;
  line-height: 4px;
  padding: 5px;
  border-radius: 50%;
  color: #fff;
  box-shadow: 1px 1px 5px #000;
  border: 2px solid #fff;
  background-color: #b60000;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="marketoptionslist">
  <a><button class="btn" >
  click me
  </button></a>
  <a><button class="btn">
  click me
  </button ></a>
  <a><button class="btn">
  click me
  </button></a>
  <a><button class="btn">
  click me
  </button></a>
</div>

<span id="notify" class="notification"></span>

and suggestions?

share|improve this question
  • Are you trying to build a toggle system? Ie. the third click should add one, and the fourth click should subtract – Rory McCrossan Feb 14 at 10:00
  • It sounds like the counter will always toggle between 0 and 1 when you click. Have you thought about how you could achieve that within your .on('click',... handler? – Steve Greatrex Feb 14 at 10:01
  • use simply a flag and declare it as false and in in button click check if its fals e or true if false then it will be first click and then do your logic and change it as true and in the coming hits you can check the same logic if it is true then go for decrement logic – Arunprasanth K V Feb 14 at 10:01

5 Answers 5

active oldest votes
up vote 3 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.396751 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO