我发现这个非常短的干净代码只允许文本字段中的数字字符。目前它只涵盖数字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/
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>
答案 0 :(得分:6)
尝试:
$(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/
答案 1 :(得分:1)
通过上述答案,您仍然可以执行0.23.12.33,这不是有效数字。
http://www.texotela.co.uk/code/jquery/numeric/是一个很棒的小插件,我经常使用它。它可以解决上述问题。
答案 2 :(得分:0)
$("#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();
}
}
});
使用键码110和190