[英]Increment the value of an input type number using jQuery
I'm trying to increment the value of an input type="number"
element using jQuery
.我正在尝试使用
jQuery
增加input type="number"
元素的值。 However I currently have it so that every time I press the add button it appends 1 to the value so I get a value like 1111
etc etc...但是,我目前拥有它,因此每次我按下添加按钮时,它都会将 1 附加到该值上,这样我就会得到一个类似
1111
等的值...
I was able to do it fine when it was set to type=text
but it was not ideal as I was trying to increment the values so all that was happening was the counter was being appended to the value of the input box.当它设置为
type=text
时,我能够做得很好,但它并不理想,因为我试图增加值,所以发生的所有事情都是将计数器附加到输入框的值。 Output was like this 01 02 03 04
.输出是这样的
01 02 03 04
。
Anyways, Currently I'm doing this:无论如何,目前我正在这样做:
<input type="number" class="qty" id="book-qty" disabled/>
<span class="add">ADD</span>
var count = 0;
$('.minus').click(function () {
if (count - 1 >= 0) {
count = parseInt($(this).parent().find('#book-qty').val());
count = count - 1;
$(this).parent().find('#book-qty').val(count);
} else {
alert('Nothing to take away!');
}
});
$('.add').click(function () {
count = $(this).parent().find('#book-qty').val();
count = count + 1;
$(this).parent().find('#book-qty').val(count);
});
I've a jsFiddle I'm working on here:我有一个 jsFiddle 我在这里工作:
https://jsfiddle.net/javacadabra/L1sLr921/ https://jsfiddle.net/javacadabra/L1sLr921/
Does anyone know?有人知道吗?
you need to parse the value to an integer otherwise it get treated as a string so it will concatenate instead of add together.您需要将值解析为整数,否则它会被视为字符串,因此它将连接而不是加在一起。
count = parseInt($('#book-qty').val());
Also you need to specify a default value for your inputs like stated by Mex.您还需要为您的输入指定一个默认值,如 Mex 所述。
Set the default value to 0 with "value=0" on the input type=number.在输入 type=number 上使用“value=0”将默认值设置为 0。
Then use:然后使用:
count = parseInt(count) + 1;
instead of:代替:
count = count + 1;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.