简体   繁体   English

使用jQuery增加输入字段值

[英]Increment input field value with jQuery

What is the shortest way in jQuery (or pure JavaScript) to increment the value of an input field? jQuery(或纯JavaScript)中增加输入字段值的最短路径是什么?

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. 现在在需要的时间和地点调用increment()

Try this: 试试这个:

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

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

DEMO 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: 这里不需要jQuery,而是使用纯JavaScript:

document.getElementById('counter').value++;

Demo: http://jsfiddle.net/RDMPq/ 演示: http//jsfiddle.net/RDMPq/

You can move the increment to a function that accepts dynamic IDs for increased portability: 您可以将增量移动到接受动态ID的功能,以提高可移植性:

function incrementInput(id){
    document.getElementById(id).value++;
}

Demo: http://jsfiddle.net/uyuGY/ 演示: http//jsfiddle.net/uyuGY/

You could try this: 你可以试试这个:

jQuery: 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: 你的HTML:

<input id="counter" type="hidden" name="counter" value="1">
<button id="increment">Increment field</button>

Hope that helps. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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