-4

When receiving a message in my chat program, count should increment by 1. But it jumps from 1 to 12. Why is that?

$("#btn").click(function(){
  var count = Number($('.badge').text());
  $('.badge').text(count + 1);
});
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.11.0/umd/popper.min.js" integrity="sha384-b/U6ypiBEHpOf/4+1nzFpr53nxSS+GLCkfwBdFNTxtclqqenISfwAzpKaMNFNmj4" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/js/bootstrap.min.js" integrity="sha384-h0AbiXch4ZDo7tp9hKZ4TsHbi047NrKGLO3SEJAg45jXxnGIfYzk4Si90RDIqNm1" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="badge">0</span>

<button id="btn"></button>
suonpera
  • 225
  • 1
  • 5
  • 13

1 Answers1

1

I was able to reproduce your problem by putting two elements with class badge in the same page. This causes $('.badge').text() to return 11, which is then incremented to 12 which is stored in each badge. If you only intended to have one badge, just get rid of the other one. Or perhaps you meant to give them each different names?

Otherwise, you could increment each badge separately:

$(".badge").each(function(idx){
    var count = Number($(this).text());
    $(this).text(count + 1);
});
Flight Odyssey
  • 2,267
  • 18
  • 25
  • actually I have two .badge... So I guess it would be better to call them id="badge1" and id="badge2"? – suonpera Aug 20 '17 at 08:42