Mahoni
Mahoni

Reputation: 7466

Increment input field value with jQuery

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

Answers (5)

JuaNPa
JuaNPa

Reputation: 209

I think that the shortest way is:

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

or

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

Upvotes: 21

Robert
Robert

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

Michael Giovanni Pumo
Michael Giovanni Pumo

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

thecodeparadox
thecodeparadox

Reputation: 87073

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

Upvotes: 43

qwertymk
qwertymk

Reputation: 35334

Try this:

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

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

DEMO

Upvotes: 11

Related Questions