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

javascript - how to increment text box value using jquery? - Stack Overflow

programmeradmin9浏览0评论

I want increment #hidtr value in jquery.

<script type="text/javascript">  
    $('#hidtr').val(parseInt($('#hidtr').val()+1));     
    alert($('#hidtr').val());  
</script>

I want increment #hidtr value in jquery.

<script type="text/javascript">  
    $('#hidtr').val(parseInt($('#hidtr').val()+1));     
    alert($('#hidtr').val());  
</script>
Share Improve this question edited Jun 23, 2012 at 7:02 thecodeparadox 87.1k22 gold badges141 silver badges164 bronze badges asked Jun 23, 2012 at 6:38 Mariselvam PanneerselvamMariselvam Panneerselvam 1711 silver badge10 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 11

Try this

var val = $('#hidtr').val();
$('#hidtr').val((val*1)+1); 

I will preferred below approach because don't need to use $('#hidtr').val() twice and you can also process the value as you like.

$('#hidtr').val(function(i, oldVal) {
  return parseInt(oldVal || 0, 10) + 1; // oldVal || 0 if initial is empty
});  
alert($('#hidtr').val()); 

DEMO


If you don't want to use above approach then follow: (@charlietfl mentioned)

var hidtr = $('#hidtr'), // store the reference, not use multiple time
    val = parseInt( hidtr.val(), 10 ) || 0, // peek the value
    inc = val + 1;  // increment value

hidtr.val(inc); // set value

Note

parseInt(value, radix) accept two parameter, first one is value and second one is radix(for integer it will 10, for hex it will 16 and so on).

.val() jquery accept a value as parameter to set and also a function (with two arguments index and old value).

Try

$('#hidtr').val(parseInt($('#hidtr').val(),10)+1);

You had the brackets in the wrong place, also Radix is reended, see the docs for paraeInt here

You need to wrap it in ready callback and make adjustments to brackets

$(function(){
   $('#hidtr').val(parseInt($('#hidtr').val(),10) || 0 +1);
    alert($('#hidtr').val());

});

See: jQuery Docs : How jQuery Works for explanation of why it needs to be wrapped

WHen using a selector more than once in a handler or function, it is better to cache it

$(function(){
    var $hidtr= $('#hidtr');
     var val=$hidtr.val();
   $hidtr.val(parseInt( val,10)  || 0 +1);
    alert( $hidtr.val());

});

Or another working demo http://jsfiddle/AuJv2/5/ OR in case of initial empty input: http://jsfiddle/AuJv2/8/

Please note parseInt($('#hidtr').val()+1) should be parseInt($('#hidtr').val())+1

Hope this helps,

code

var num = parseInt($('#hidtr').val()) || 0;
$('#hidtr').val(parseInt(num)+1);
alert($('#hidtr').val());

OR

$('#hidtr').val(parseInt($('#hidtr').val())+1);
alert($('#hidtr').val());

​
发布评论

评论列表(0)

  1. 暂无评论