Javascript 使用 jQuery 增加输入字段值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11546228/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Increment input field value with jQuery
提问by Mahoni
What is the shortestway 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">
回答by thecodeparadox
$('#counter').val( function(i, oldval) {
return parseInt( oldval, 10) + 1;
});
OR
或者
$('#counter').val( function(i, oldval) {
return ++oldval;
});
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()
就在您需要的时间和地点拨打电话。
回答by JuaNPa
I think that the shortest way is:
我认为最短的方法是:
$('#counter').get(0).value++
or
或者
$('#counter').get(0).value--
回答by RobB
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++;
}
回答by Michael Giovanni Pumo
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.
希望有帮助。