Reputation: 906
I'm trying to increase a number inside a when an event happens. Eg. button click. On the first event the code works fine, but on following events the numbers 'double up' and I'm not sure why.
EG. HTML:
<div>
<span class="userpointshead"> 130 </span>
<button class="jquery-tester">Button</button>
</div>
JQuery:
$('.jquery-tester').click(function() {
var points = parseInt($('.userpointshead').text());
$('.userpointshead').text(points+5);
});
On the first button click, the contents of .userpointshead
will be updated to 135
. On the second click they will be updated to 135140
. On the third click it updates to 135140135145
and so on.
I want it to go from 130 - 135 - 140 - 145 - etc.
I have also tried the following with the same results:
$('.jquery-tester').click(function() {
var points = parseInt($('.userpointshead').text().trim(), 10);
var newpoints = points + 5;
$(".userpointshead").html(newpoints);
});
I feel I'm missing something very obvious but not sure what.
UPDATE: I have tried the same code with a new <span>
and it works as I'd like. I still have know idea why the original won't work.. it's just a span with a number in.
Upvotes: 0
Views: 100
Reputation: 906
Well I have more or less solved it, although I do not understand or like the solution.
Adding an extra class to the <span>
and executing the jquery on the new class let everything work as it should.
<span class="userpointshead user-points"> 130 </span>
<button class="jquery-tester">Button</button>
$('.jquery-tester').click(function() {
var points = parseInt($('.user-points').text());
$('.user-points').text(points+5);
});
I have no other jquery/javascript interfering with .userpointshead
in my project and I can't understand why it wouldn't work.
Upvotes: 0
Reputation: 1018
I simply tried this and its working fine.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.jquery-tester').click(function() {
var points = parseInt($('.userpointshead').text());
$('.userpointshead').text(points+5);
});
});
</script>
</head>
<body>
<div>
<span class="userpointshead"> 130 </span>
<button class="jquery-tester">Button</button>
</div>
</body>
</html>
Upvotes: 1
Reputation: 36
Your coude should work fine. Maybe try this to check if the problem is not elsewhere:
$('.userpointshead').text(parseInt(points)+5);
Upvotes: 0