仅允许数字和一位小数 [英] Allowing only numbers and one decimal
问题描述
伙计和女孩我有这段JavaScript代码,只允许数字和一个小数周期。我遇到的问题是,当我切换到我的文本框控件时,它会突出显示该值,但我按了退格键以擦除然后输入一个数字。这是我想要阻止的额外击键。
Guys and gals i have this piece of JavaScript code that only allows for numbers and one decimal period. The problem i'm having is that when i tab over to my textbox controls it highlights the value but i have press backspace to erase then enter a number. That is an extra keystroke that i want to prevent.
找到创建它的人的道具( http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction )这是代码。我把它放在keyUp事件上。
Props to the guy who created it found (http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction) and here is the code. I put this on keyUp event.
<script>
// Retrieve last key pressed. Works in IE and Netscape.
// Returns the numeric key code for the key pressed.
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function restrictChars(e, obj)
{
var CHAR_AFTER_DP = 2; // number of decimal places
var validList = "0123456789."; // allowed characters in field
var key, keyChar;
key = getKey(e);
if (key == null) return true;
// control keys
// null, backspace, tab, carriage return, escape
if ( key==0 || key==8 || key==9 || key==13 || key==27 )
return true;
// get character
keyChar = String.fromCharCode(key);
// check valid characters
if (validList.indexOf(keyChar) != -1)
{
// check for existing decimal point
var dp = 0;
if( (dp = obj.value.indexOf( ".")) > -1)
{
if( keyChar == ".")
return false; // only one allowed
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
}
else return true;
}
// not a valid character
return false;
}
</script>
推荐答案
如果你不能使用已经稳定的井知道库,你可以尝试这样的事情:
If you can't use an already stable and well-know library, you can try something like this:
document.write('<input id="inputField" onkeyup="run(this)" />');
function run(field) {
setTimeout(function() {
var regex = /\d*\.?\d?/g;
field.value = regex.exec(field.value);
}, 0);
}
我知道它不会阻止出现错误的字符,但它有效。
I know it doesn't prevent the wrong char to appear, but it works.
PS:那个 setTimeout(...,0)
是一个在值之后执行函数的技巧该字段已被修改。
PS: that setTimeout(..., 0)
is a trick to execute the function after the value of the field has already been modified.
这篇关于仅允许数字和一位小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!