具有最小和最大范围的 jquery 数字文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2013229/
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
jquery numeric textbox with min and max ranges
提问by leora
i see this question but none of the solutions support min and max values range
我看到这个问题,但没有一个解决方案支持最小值和最大值范围
How to allow only numeric (0-9) in HTML inputbox using jQuery?
如何使用 jQuery 在 HTML 输入框中只允许数字 (0-9)?
I see that http://jstepper.emkay.dk/attempts to do this but seems very buggy as it allows you to enter multiple decimal places and other characters such as ";".
我看到http://jstepper.emkay.dk/尝试这样做,但似乎很麻烦,因为它允许您输入多个小数位和其他字符,例如“;”。
is there i way i can use one of these solutions and also say, only support min of 0 and max of 100 in the textbox entry?
我有什么方法可以使用这些解决方案之一,并且还说,在文本框条目中只支持最小值为 0 和最大值为 100?
回答by EmKay
回答by Anurag
HTML5 way of adding such fields. Works in Chrome and Safari:
添加此类字段的 HTML5 方式。适用于 Chrome 和 Safari:
<input type="range" min="0" max="100" step="1" />
A complete example:
一个完整的例子:
<input id="picker" type="range" min="0" max="100" step="1" onchange="$('#pickerValue').text(this.value)" />
<div id="pickerValue"></div>
回答by Anurag
Create a custom type of text box that only accepts ranges. Something like this should work:
创建仅接受范围的自定义类型的文本框。这样的事情应该工作:
function RangeTextBox(min, max) {
this.min = min;
this.max = max;
this.textBox = $("<input type='text'>");
// Disallow non-numbers from being typed in box
this.textBox.keydown(function(event) {
var isNotBackspaceOrDelete = event.keyCode != 46 && event.keyCode != 8;
var isNotInteger = event.keyCode < 48 || event.keyCode > 57;
if(isNotBackspaceOrDelete && isNotInteger) {
event.preventDefault();
}
});
// Check for a valid range
this.textBox.keyup(function(event) {
var textBox = event.target;
var isNotInRange = (textBox.value < min) || (textBox.value > max);
if (isNotInRange) {
textBox.value = textBox.value.slice(0, -1);
}
});
return this.textBox;
}
To use it in, simple create a new TextBox by calling new RangeTextBox(min, max)
. For example
要在其中使用它,只需通过调用创建一个新的 TextBox new RangeTextBox(min, max)
。例如
$(document).ready(function() {
$("body").append(new RangeTextBox(1, 18));
});
Disclaimer: This suffers from the same problem as listed by Harmen in the other answer of field not accepting a value like 2 for the number "26" if minimum value is 6 as 2 < 6. You could use a timer, or actually move this check outside of the keyup
and keydown
events, and check onblur
or onchange
instead. That would allow invalid data to enter the field though but its a lot less annonying.
免责声明:如果最小值是 6 作为 2 < 6,这与 Harmen 在字段的另一个答案中列出的相同的问题不接受数字“26”的 2 之类的值。您可以使用计时器,或者实际移动它检查keyup
和keydown
事件之外,并检查onblur
或onchange
代替。虽然这将允许无效数据进入该字段,但它的烦人程度要低得多。
Edit: This solution let's you enter anything, but flags all invalid input including out of ranges.
编辑:此解决方案可让您输入任何内容,但会标记所有无效输入,包括超出范围。
function RangeTextBox(min, max) {
this.min = min;
this.max = max;
this.textBox = $("<input type='text'>");
// Check for a valid range
this.textBox.keyup(function(event) {
var textBox = event.target;
var value = parseInt(textBox.value);
var isNotNumeric = !/^[0-9]+$/.test(textBox.value);
var isOutsideRange = (value < min) || (value > max);
if (isNotNumeric || isOutsideRange) {
$(textBox).addClass('error');
}
else {
$(textBox).removeClass('error');
}
});
return this.textBox;
}
And the stylesheet:
和样式表:
<style type="text/css">
.error {
color: red;
}
回答by StormDog
Textbox MIN MAX - jQuery function
文本框 MIN MAX - jQuery 函数
Here is a way to for example, "only support min of 0 and max of 100 in a textbox entry" using jQuery. It works by returning your entry to what it was before - if you enter a key that results in the value being less than MIN or more that MAX. You can set a flag to accept only integers.
例如,这是一种使用 jQuery 的方法,例如“在文本框条目中仅支持最小 0 和最大 100”。它的工作原理是将您的条目返回到之前的状态 - 如果您输入的键导致值小于 MIN 或大于 MAX。您可以设置一个标志以仅接受整数。
The HTML tag would look like this: (JSFIDDLE)
HTML 标记如下所示:( JSFIDDLE)
<input type="text" class="maxmin" min="0" max="100" intOnly="true" />
Then you'd run this JavaScript in your document ready code:
然后,您将在文档就绪代码中运行此 JavaScript:
// Run this on document ready to allow only numbers between
// max and min to be entered into textboxes with class="maxmin".
// Attributes max, min, and intOnly="true/false" are set in the tag.
// Min should probably be "0" or "1", or max and min could be single digits.
// Otherwise for example, if min=5, you couldn't enter 23 because 2 < 5.
$(".maxmin").each(function () {
var thisJ = $(this);
var max = thisJ.attr("max") * 1;
var min = thisJ.attr("min") * 1;
var intOnly = String(thisJ.attr("intOnly")).toLowerCase() == "true";
var test = function (str) {
return str == "" || /* (!intOnly && str == ".") || */
($.isNumeric(str) && str * 1 <= max && str * 1 >= min &&
(!intOnly || str.indexOf(".") == -1) && str.match(/^0\d/) == null);
// commented out code would allow entries like ".7"
};
thisJ.keydown(function () {
var str = thisJ.val();
if (test(str)) thisJ.data("dwnval", str);
});
thisJ.keyup(function () {
var str = thisJ.val();
if (!test(str)) thisJ.val(thisJ.data("dwnval"));
})
});
I'm new to this, so any constructive comments would be appreciated.
我是新手,所以任何建设性的意见将不胜感激。
回答by jerone
I've created an jQuery SpinControlthat supports min, max and step. It first checks if a SpinControl already is supported by the browser (Opera), before it adds a custom one.
我创建了一个支持最小、最大和步长的 jQuery SpinControl。在添加自定义控件之前,它首先检查浏览器 (Opera) 是否已支持 SpinControl。
回答by Harmen
Here is an example of how your script could look like:
以下是您的脚本外观示例:
var value, min=6, max=100;
function isNumberPressed(k) {
// 48-57 are number 0-9 on a normal keyboard, 96-105 are keypad numbers
return (k > 47 && k < 58) || (k > 95 && k < 106) ? true : false;
}
function isValidNumber(v){
// Check if a valid number is entered
return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}
$(document).ready(function() {
$("#test").keydown(function(e) {
// See if a valid key is pressed
if(isNumberPressed(e.keyCode)){
if(isValidNumber($(this).val())) value = $(this).val();
}
// Do nothing if unallowed keys are pressed
else if(e.keyCode != 46 && e.keyCode != 8) return false;
}).keyup(function(){
// If the value, including the latest number that's added, is not valid (to high or to low), show the old value again
if(isValidNumber($(this).val()) == false){
$(this).val(value);
}
});
});
But it has a big disadvantage, you can't enter 26 if the minimum is 6, because 2 < 6. This is not a problem if you have a minimum less than or equal to 10.
但是它有一个很大的缺点,如果最小值是6,就不能输入26,因为2 < 6。如果最小值小于等于10,这不是问题。
However, if your minimum is more than 10, you could consider this code:
但是,如果您的最小值超过 10,则可以考虑使用以下代码:
var timer, min=36, max=100;
function isValidNumber(v){
// Check if a valid number is entered
return (parseInt(v, 10) >= min && parseInt(v, 10) <= max) ? true : false;
}
$(document).ready(function() {
$("#test").keydown(function(e) {
that = this;
// Clear the timer
if(timer)
clearTimeout(timer);
// Set a new timer with a delay of one second
timer = setTimeout(function(){
if(isValidNumber($(that).val()) == false) $(that).addClass('error');
else $(that).removeClass('error');
}, 1000);
});
});
It checks the input with a delay of one second. You need some CSS code for this, for example:
它以一秒的延迟检查输入。为此,您需要一些 CSS 代码,例如:
input.error {
border: 2px solid red;
}
Both scripts check the values on the fly, which is a great method.
这两个脚本都在运行中检查值,这是一个很好的方法。
回答by Cheung
JStepper have a bug, I try the tester in their site. http://jstepper.emkay.dk/Default.aspx
JStepper 有一个错误,我在他们的网站上尝试测试器。 http://jstepper.emkay.dk/Default.aspx
apple the rules, but i can input the text : 8778.09999
苹果规则,但我可以输入文本:8778.09999
回答by QMaster
I searched and finally i understand entered value must be check in three event. keydown, keypress and keyup and any of them has own responsibilities. keypress: Check the key pressed and decided about entered character. Then if it is numeric let it otherwise prevent the action. As you can see i tried to check range here
我搜索了,最后我明白输入的值必须在三个事件中检查。keydown、keypress 和 keyup 以及它们中的任何一个都有自己的职责。keypress:检查按下的键并决定输入的字符。然后,如果它是数字,则让它阻止该操作。正如你所看到的,我试图在这里检查范围
//var final = val + String.fromCharCode(charCode);
//alert(final);
//if (final < min || final > max)
// return false;
but we just have new character and value before that. so that is wrong way if we try to check sum of them because maybe user selected some part of the value and new character standing rather. suppose max range is 100 and we have "345" in Input and user selected "34" now user press "2" and the result must be "25", but sum of "345" + "2" is 347 and function prevent that. So i decided to use keyup event to check range and correct value. Finally keydown used to check up and down arrow and control value when browser support HTML5 number type of input without changing like keypress so you can don't use that.
但在此之前,我们只是有了新的角色和价值。所以如果我们尝试检查它们的总和,那是错误的方法,因为也许用户选择了值的某些部分和新角色。假设最大范围是 100 并且我们在 Input 中有 "345" 并且用户选择了 "34" 现在用户按下 "2" 并且结果必须是 "25",但是 "345" + "2" 的总和是 347 并且函数阻止了. 所以我决定使用 keyup 事件来检查范围和正确的值。最后,当浏览器支持 HTML5 数字类型输入时,keydown 用于检查上下箭头和控制值,而不像 keypress 那样更改,因此您不能使用它。
I wrote a simple script and hope that help. You can see it in http://jsfiddle.net/QMaster/r4hwr3a6/
我写了一个简单的脚本,希望有所帮助。您可以在http://jsfiddle.net/QMaster/r4hwr3a6/ 中看到它