Javascript 使用jQuery向输入字段添加最大值
我使用一个简单的减号/加号jsfiddle在输入字段中添加或删除一个数字。然而,我试图找出设置最大值的最佳方法,这意味着如果用户试图键入大于10的数字或使用加号功能,则无法超过10。实现这一目标的最佳方式是什么Javascript 使用jQuery向输入字段添加最大值,javascript,jquery,html,Javascript,Jquery,Html,我使用一个简单的减号/加号jsfiddle在输入字段中添加或删除一个数字。然而,我试图找出设置最大值的最佳方法,这意味着如果用户试图键入大于10的数字或使用加号功能,则无法超过10。实现这一目标的最佳方式是什么 jQuery(document).ready(function(){ // This button will increment the value $('.qtyplus').click(function(e){ // Stop acting like a button
jQuery(document).ready(function(){
// This button will increment the value
$('.qtyplus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[name='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
// This button will decrement the value till 0
$(".qtyminus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[name='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[name='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[name='+fieldName+']').val(0);
}
});
}))
您不需要使用
加号
和减号
按钮来实现这一点<使用min
和max
属性输入typenumber
如果您只是对JS/jQuery解决方案感兴趣,只需更改第11行:
if (!isNaN(currentVal) && currentVal < 10) {
^~~~~~~~~~~~~~~~~~~^---------[Add this to line 11
有没有办法让它在达到10点时保持在那里?而不是重置为0。而且,他们仍然有可能输入自己的号码,我想确保他们不能输入t@Lynx请参阅更新。如果手动输入大于10的数字,则在模糊
、键
、单击
、或聚焦
(在另一个元素上)等上,该值将更改为10。这将是一个简洁的解决方案。然而,浏览器支持似乎是缺乏的。我需要在旧的浏览器上也使用它。
$('input[name=' + fieldName + ']').val(10);
^^-----[Change 0 into 10