简体   繁体   中英

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

Try this:

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

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

DEMO

I think that the shortest way is:

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

or

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

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/

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM