10

I want increment #hidtr value in jquery.

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

5 Answers 5

11

Try this

var val = $('#hidtr').val();
$('#hidtr').val((val*1)+1); 
Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

Dude, the initial value is empty.
1

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

2 Comments

This is code execute but not value added. $('#hidtr').val() is nan come
@panneerselvam What is the initial value ??
1

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

});

Comments

0

Or another working demo http://jsfiddle.net/AuJv2/5/ OR in case of initial empty input: http://jsfiddle.net/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());

​

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.