Reputation: 2883
I have a button which has a value each time a user clicks that button the value suppose to go up by 1. This works but not how I would like for instance for there are no clicks then the buttons value is 0 if a user clicks then the value goes to 01 instead of 1. How can I go about resolving this? I been stuck admittingly I am new to Jquery.
var cfollowers = $('#cfollowers').val()+1;
$('#cfollowers').val(cfollowers);
<input type="button" id="cfollowers" value="0" />
Upvotes: 0
Views: 79
Reputation: 2085
Your issue is that the value of an input element is reprented as a string, so you are concatenating strings rather than adding integers. Just add a parseInt call to your code to fix the issue:
<input type="button" id="cfollowers" value="0" />
<script>
$('#cfollowers').click( function() {
var cfollowers = parseInt($('#cfollowers').val())+1;
$('#cfollowers').val(cfollowers);
});
</script>
Edit: docodemore makes a good point! A better way to approach this would be to store the value of the button as a separate variable.
<input type="button" id="cfollowers" value="0" />
<script>
var cfollowers = 0;
$('#cfollowers').click( function() {
cfollowers++;
$('#cfollowers').val(cfollowers);
});
</script>
Upvotes: 3