22

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">

5 Answers 5

43
$('#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.

Sign up to request clarification or add additional context in comments.

Comments

21

I think that the shortest way is:

$('#counter').get(0).value++ 

or

$('#counter').get(0).value--

Comments

11

Try this:

var $input = $('#counter');

$input.val( +$input.val() + 1 );​

DEMO

4 Comments

Would you suggest to use your selector over $("#counter"), if yes, why? So you don't have to assign an extra id?
what is the purpose of the + in '+$input.val()'?
@Mahoni I didn't see that there was an id attr, I updated the answer
@NathanReed so that it doesn't think I want to do "1" + 1 which will be 11 , and instead first converts it into a number
8

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/

Comments

1

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.

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.