Reputation: 4474
I'm trying to increment input text value by 1 when clicked. It's a really simple task but i'm not able to make it working. Here is the code:
<script type="text/javascript">
$('#field').bind('click', function(){
old_value = $(this).attr('value');
$(this).attr('value', (old_value+1));
})
</script>
<form action="">
<input type="text" value="1" id="field"/>
</form>
And after clicking on input, it's value is not incremented. Instead of that, number 1
is added at the end of the value so i.e. after 3 clicks the input value is 1111
. Have you any ideas what am i doing wrong? Thanks in advance.
Upvotes: 1
Views: 3630
Reputation: 83358
The unary +
operator can conveniently turn a string into a number
$(this).attr('value', (+old_value + 1));
Or you can use parseInt
like the other answers describe.
Upvotes: 2
Reputation: 84140
You need to typecast as all form values are passed around as strings.
$('#field').bind('click', function(){
old_value = parseInt($(this).attr('value'), 10);
$(this).attr('value', (old_value+1));
})
Whatever you do don't forget to pass a radix (base) through to the parseInt function!
If you forget, this might happen:
parseInt("010") # 8
Upvotes: 6
Reputation: 887215
You need to parse the string into a number:
parseInt($(this).val(), 10)
Upvotes: 0