javascript jquery - 纯数字文本字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11473522/
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 Only Text Field
提问by user1176783
I found this very short clean code to only allow numeric chars in a text field. Currently it only covers numbers 0-9 and backspace and delete. I wanted it to also include decimal/period, so I have been fighting with this to simply include keycode 110 and/or 190. I can not get it to work. Can anyone see what I am doing wrong?
我发现这个非常短的干净代码只允许在文本字段中使用数字字符。目前它只涵盖数字 0-9 和退格和删除。我希望它也包含十进制/句点,所以我一直在努力解决这个问题,只包含键码 110 和/或 190。我无法让它工作。谁能看到我做错了什么?
$(document).ready(function() {
$('input.numberinput').bind('keypress', function(e) {
return ( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57) ) || (e.which!=110) ? false : true ;
});
});
jsfiddle here: http://jsfiddle.net/justmelat/EN8pT/
jsfiddle在这里:http://jsfiddle.net/justmelat/EN8pT/
html
html
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber1" id="txtNumber1" value="" class="numberinput" />
<div class="label">Enter a number:</div>
<input type="text" name="txtNumber2" id="txtNumber2" value="" class="numberinput" />
</div>
回答by Daniel Li
Try:
尝试:
$(document).ready(function () {
$('input.numberinput').bind('keypress', function (e) {
return !(e.which != 8 && e.which != 0 &&
(e.which < 48 || e.which > 57) && e.which != 46);
});
});?
JsFiddle: http://jsfiddle.net/EN8pT/1/
JsFiddle:http: //jsfiddle.net/EN8pT/1/
回答by Peter Munnings
With the above answer you can still do 0.23.12.33 which is not a valid number.
有了上面的答案,你仍然可以做 0.23.12.33 这不是一个有效的数字。
http://www.texotela.co.uk/code/jquery/numeric/is a great little lightweight plugin that I have used a lot. It takes the pain out of the above.
http://www.texotela.co.uk/code/jquery/numeric/是一个很棒的轻量级插件,我用过很多。它消除了上述痛苦。
回答by Mario Gonzales Flores
$("#input").keydown(function(event) {
var theEvent = event || window.event;
var key = theEvent.keyCode || theEvent.which;
// Allow: backspace, delete, tab, escape, and enter
if ( key == 46 || key == 8 || key == 9 || key == 27 || key == 13 || key == 110 || key == 190 ||
// Allow: Ctrl+A
(key == 65 && theEvent.ctrlKey === true) ||
// Allow: home, end, left, right
(key >= 35 && key <= 39)) {
// let it happen, don't do anything
return;
}
else {
// Ensure that it is a number and stop the keypress
if (theEvent.shiftKey || (key < 48 || key > 57) && (key < 96 || key > 105 )) {
theEvent.preventDefault();
}
}
});
with keycode 110 and 190
使用键码 110 和 190