Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to increment text box value using jquery?

I want increment #hidtr value in jquery.

<script type="text/javascript">  
    $('#hidtr').val(parseInt($('#hidtr').val()+1));     
    alert($('#hidtr').val());  
</script>
like image 722
Mariselvam Panneerselvam Avatar asked Jun 23 '12 06:06

Mariselvam Panneerselvam


4 Answers

Try this

var val = $('#hidtr').val();
$('#hidtr').val((val*1)+1); 
like image 85
Karthick V Avatar answered Nov 02 '22 17:11

Karthick V


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).

like image 34
thecodeparadox Avatar answered Nov 02 '22 15:11

thecodeparadox


Try

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

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

like image 44
Manse Avatar answered Nov 02 '22 16:11

Manse


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());

});
like image 29
charlietfl Avatar answered Nov 02 '22 16:11

charlietfl