最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Sum instead of concatenate - Stack Overflow

programmeradmin1浏览0评论

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.

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.

Share Improve this question edited Mar 2, 2012 at 0:07 Adam Rackis 83.4k57 gold badges278 silver badges400 bronze badges asked Mar 2, 2012 at 0:01 mbajurmbajur 4,4945 gold badges54 silver badges84 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

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 

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.

You need to parse the string into a number:

parseInt($(this).val(), 10)
发布评论

评论列表(0)

  1. 暂无评论