jQuery 如何限制“正数”仅作为文本框的输入(仅允许“-99”)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7937860/
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
How to restrict "positive numbers" only as input to textbox (allow "-99" ONLY)?
提问by reshma k
How to restrict "positive numbers" only as input to textbox (allow "-99" ONLY) using jQuery validator plugin?
如何使用 jQuery 验证器插件限制“正数”仅作为文本框的输入(仅允许“-99”)?
回答by Sampath
Without using any Pluginyou can easily do that by using below mentioned code.
在不使用任何插件的情况下,您可以使用下面提到的代码轻松地做到这一点。
HTML
HTML
<input type="text" name="returnRetailQuantity" id="returnRetailQuantity" />
jQuery Code
jQuery 代码
//for allow only positive integers
$(document).ready(function(){
$("#returnRetailQuantity").keydown(function (event) {
if (event.shiftKey) {
event.preventDefault();
}
if (event.keyCode == 46 || event.keyCode == 8) {
}
else {
if (event.keyCode < 95) {
if (event.keyCode < 48 || event.keyCode > 57) {
event.preventDefault();
}
}
else {
if (event.keyCode < 96 || event.keyCode > 105) {
event.preventDefault();
}
}
}
});
});
Hope this will help you.
希望这会帮助你。
回答by SaQiB
回答by photo_tom
The easiest that I've used is http://digitalbush.com/projects/masked-input-plugin/.
我用过的最简单的是http://digitalbush.com/projects/masked-input-plugin/。
There is a simple javascript function at http://michael.theirwinfamily.net/articles/jquery/creating-input-fields-only-accept-integers-jquery
http://michael.theirwinfamily.net/articles/jquery/creating-input-fields-only-accept-integers-jquery有一个简单的 javascript 函数
回答by w.Daya
<input type="number" id="num" name="anyname" min='0' />
<script>
$(document).ready(function()
{
var num = $('#num').val();
$('#num').blur(function()
{
if(num<0)
{
if(num==-99)
{
alert('Valid number');
}
else
{
alert('Invalid number');
}
}
else
{
alert('Valid number');
}
});
});
</script>