伙计们,我有这段 JavaScript 代码,它只允许数字和一个小数点。我遇到的问题是,当我切换到我的文本框控件时,它会突出显示该值,但我按退格键删除然后输入一个数字。这是我想防止的额外击键。
创建它的人的 Prop 找到了( http://www.coderanch.com/t/114528/HTML-CSS-JavaScript/decimal-point-restriction ),这是代码。我把它放在 keyUp 事件上。
<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>
最佳答案
<input type="text" class="decimal" value="" />
在 Js 中使用这个
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});
检查这个 fiddle :http://jsfiddle.net/2YW8g/
这对我有用,我从“Nickalchemist”那里得到了这个答案并且不相信它。
关于javascript - 只允许数字和一位小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14609521/