Javascript 文本框中的最大值和最小值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8761852/
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
Maximum and minimum values in a textbox
提问by BruceyBandit
I have a textbox. Is there a way where the highest value the user can enter is 100 and the lowest is 0?
我有一个文本框。有没有办法让用户可以输入的最高值是 100,最低值是 0?
So if the user types in a number more than 100 then it will automatically change the value to 100 using a keyup() function and if user types in a number less than 0 it will display as 0?
因此,如果用户输入的数字大于 100,那么它会使用 keyup() 函数自动将值更改为 100,如果用户输入的数字小于 0,它将显示为 0?
My textbox is below:
我的文本框如下:
<input type="text" name="textWeight" id="txtWeight" maxlength="5"/>%</td>
Can this be done using JavaScript?
这可以使用 JavaScript 完成吗?
回答by Nikoloff
Here's a simple function that does what you need:
这是一个简单的函数,可以满足您的需求:
<script type="text/javascript">
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return min;
else if(parseInt(value) > max)
return max;
else return value;
}
</script>
<input type="text" name="textWeight" id="txtWeight" maxlength="5" onkeyup="this.value = minmax(this.value, 0, 100)"/>
If the input is not numeric it replaces it with a zero
如果输入不是数字,则将其替换为零
回答by jondavidjohn
If you are OK with HTML5 it can be accomplished without any JavaScript code at all...
如果你对 HTML5 没问题,它可以在没有任何 JavaScript 代码的情况下完成......
<input type="number" name="textWeight" id="txtWeight" max="5" min="0" />
Otherwise, something like...
否则,像...
var input = document.getElementById('txtWeight');
input.addEventListener('change', function(e) {
var num = parseInt(this.value, 10),
min = 0,
max = 100;
if (isNaN(num)) {
this.value = "";
return;
}
this.value = Math.max(num, min);
this.value = Math.min(num, max);
});
This will only reset the values when the input looses focus, and clears out any input that can't be parsed as an integer...
这只会在输入失去焦点时重置值,并清除任何无法解析为整数的输入......
OBLIGATORY WARNING
强制性警告
You should alwaysperform adequate server-side validation on inputs, regardless of client-side validation.
无论客户端验证如何,您都应该始终对输入执行足够的服务器端验证。
回答by Evert
I would typically do something like this (onblur), but it could be attached to any of the events:
我通常会做这样的事情(onblur),但它可以附加到任何事件:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function CheckNo(sender){
if(!isNaN(sender.value)){
if(sender.value > 100 )
sender.value = 100;
if(sender.value < 0 )
sender.value = 0;
}else{
sender.value = 0;
}
}
</script>
</head>
<body>
<input type="text" onblur="CheckNo(this)" />
</body>
</html>
回答by John Fisher
It depends on the kind of numbers and what you will allow. Handling numbers with decimals is more difficult than simple integers. Handling situations where multiple cultures are allowed is more complicated again.
这取决于数字的类型和您将允许的内容。处理带小数的数字比简单的整数更难。处理允许多种文化的情况再次变得更加复杂。
The basics are these:
基本知识是这些:
- Handle the "keypress" event for the text box. When a character which is not allowed has been pressed, cancel further processing of the event so the browser doesn't add it to the textbox.
- While handling "keypress", it is often useful to simple create the potential new string based on the key that was pressed. If the string is a valid number, allow the kepress. Otherwise, toss the keypress. This can greatlysimplify some of the work.
- Potentially handle the "keydown" event if you're concerned with keys that "keypress" doesn't handle.
- 处理文本框的“keypress”事件。当按下不允许的字符时,取消对该事件的进一步处理,以便浏览器不会将其添加到文本框。
- 在处理“按键”时,根据按下的键简单地创建潜在的新字符串通常很有用。如果字符串是有效数字,则允许 kepress。否则,扔掉按键。这可以大大简化一些工作。
- 如果您担心“keypress”无法处理的键,则可能会处理“keydown”事件。
回答by Mithrandir
Yes it can! You might consider first to set the value of maxlength to 3 and then write an event handler for the keyup-event.
是的,它可以!您可能会考虑首先将 maxlength 的值设置为 3,然后为 keyup-event 编写一个事件处理程序。
The function can evaluate the user input using regex or parseInt to validate the user input and set it to any desired value, if the input is incorrect.
如果输入不正确,该函数可以使用正则表达式或 parseInt 评估用户输入以验证用户输入并将其设置为任何所需的值。
回答by Tim
If you're not using HTML5 this is a pretty basic JavaScript form validation.
如果您不使用 HTML5,这是一个非常基本的 JavaScript 表单验证。
Side note - I'd change the value to 0 on the blur event instead of keyup (as a user I think changing the text as I'm typing would be annoying to no end).
旁注 - 我会在模糊事件上将值更改为 0 而不是 keyup (作为用户,我认为在我输入时更改文本会令人厌烦)。
回答by Ajitabh Mohanty
Its quite simple dear you can use range validator
亲爱的,它非常简单,您可以使用范围验证器
<asp:TextBox ID="TextBox2" runat="server" TextMode="Number"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox2"
ErrorMessage="Invalid number. Please enter the number between 0 to 20."
MaximumValue="20" MinimumValue="0" Type="Integer"></asp:RangeValidator>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox2" ErrorMessage="This is required field, can not be blank."></asp:RequiredFieldValidator>
otherwise you can use javascript
否则你可以使用javascript
<script>
function minmax(value, min, max)
{
if(parseInt(value) < min || isNaN(parseInt(value)))
return 0;
else if(parseInt(value) > max)
return 20;
else return value;
}
</script>
<input type="text" name="TextBox1" id="TextBox1" maxlength="5"
onkeyup="this.value = minmax(this.value, 0, 20)" />
回答by asdasd
https://jsfiddle.net/co1z0qg0/141/
https://jsfiddle.net/co1z0qg0/141/
<input type="text">
<script>
$('input').on('keyup', function() {
var val = parseInt($(this).val()),
max = 100;
val = isNaN(val) ? 0 : Math.max(Math.min(val, max), 0);
$(this).val(val);
});
</script>
or better
或更好
https://jsfiddle.net/co1z0qg0/142/
https://jsfiddle.net/co1z0qg0/142/
<input type="number" max="100">
<script>
$(function() {
$('input[type="number"]').on('keyup', function() {
var el = $(this),
val = Math.max((0, el.val())),
max = parseInt(el.attr('max'));
el.val(isNaN(max) ? val : Math.min(max, val));
});
});
</script>
<style>
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type="number"] {
-moz-appearance: textfield;
}
</style>
回答by Qamar
function
功能
getValue(input){
var value = input.value ? parseInt(input.value) : 0;
let min = input.min;
let max = input.max;
if(value < min)
return parseInt(min);
else if(value > max)
return parseInt(max);
else return value;
}
Usages
用法
changeDotColor = (event) => {
let value = this.getValue(event.target) //value will be always number
console.log(value)
console.log(typeof value)
}
回答by Ehsan
Set Attributes in CodeBehind
在 CodeBehind 中设置属性
textWeight.Attributes.Add("minimum", minValue.ToString());
textWeight.Attributes.Add("maximum", maxValue.ToString());
Result:
结果:
<input type="text" minimum="0" maximum="100" id="textWeight" value="2" name="textWeight">
By jQuery
通过 jQuery
jQuery(document).ready(function () {
var textWeight = $("input[type='text']#textWeight");
textWeight.change(function () {
var min = textWeight.attr("minimum");
var max= textWeight.attr("maximum");
var value = textWeight.val();
if(val < min || val > max)
{
alert("Your Message");
textWeight.val(min);
}
});
});