I want increment #hidtr
value in jquery.
<script type="text/javascript">
$('#hidtr').val(parseInt($('#hidtr').val()+1));
alert($('#hidtr').val());
</script>
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
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 recomended, 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());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With