What is the shortest way in jQuery (or pure JavaScript) to increment the value of an input field?
For instance
<input id="counter" type="hidden" name="counter" value="1">
so it changes to
<input id="counter" type="hidden" name="counter" value="2">
$('#counter').val( function(i, oldval) {
return parseInt( oldval, 10) + 1;
});
Demo
OR
$('#counter').val( function(i, oldval) {
return ++oldval;
});
Demo
You can wrap any one of the above code within a function and call that for further increment. For example:
function increment() {
$('#counter').val( function(i, oldval) {
return ++oldval;
});
}
Now call increment()
when and where you need.
I think that the shortest way is:
$('#counter').get(0).value++
or
$('#counter').get(0).value--
Try this:
var $input = $('#counter');
$input.val( +$input.val() + 1 );
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