Reputation: 7466
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">
Upvotes: 22
Views: 71966
Reputation: 209
I think that the shortest way is:
$('#counter').get(0).value++
or
$('#counter').get(0).value--
Upvotes: 21
Reputation: 8767
No need for jQuery here, instead use pure JavaScript:
document.getElementById('counter').value++;
Demo: http://jsfiddle.net/RDMPq/
You can move the increment to a function that accepts dynamic IDs for increased portability:
function incrementInput(id){
document.getElementById(id).value++;
}
Demo: http://jsfiddle.net/uyuGY/
Upvotes: 8
Reputation: 14784
You could try this:
jQuery:
Setup a function to do this:
function incrementVal(selector) {
var $item = selector;
var $curVal = $item.attr("value");
$item.attr("value", parseInt($curVal) + 1 );
}
Use it with the click of a button:
$("#increment").on("click",function() {
incrementVal($('#counter'));
});
Your HTML:
<input id="counter" type="hidden" name="counter" value="1">
<button id="increment">Increment field</button>
Hope that helps.
Upvotes: 1
Reputation: 87073
$('#counter').val( function(i, oldval) {
return parseInt( oldval, 10) + 1;
});
OR
$('#counter').val( function(i, oldval) {
return ++oldval;
});
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.
Upvotes: 43