Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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">
like image 999
Mahoni Avatar asked Jul 18 '12 16:07

Mahoni


3 Answers

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

like image 177
thecodeparadox Avatar answered Nov 14 '22 17:11

thecodeparadox


I think that the shortest way is:

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

or

$('#counter').get(0).value--
like image 20
JuaNPa Avatar answered Nov 14 '22 19:11

JuaNPa


Try this:

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

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

DEMO

like image 11
qwertymk Avatar answered Nov 14 '22 17:11

qwertymk