我有一个输入
和java脚本函数如下,但是当用户输入多个点时,obj.val总是返回空字符串,因此我无法限制用户从第二个点开始。我有几个使用此功能的输入,所以我需要修改功能。
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==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 == "." && dotCheck == 0)
{
return false; // only one allowed
}
else
{
// room for more after decimal point?
if( obj.value.length - dp <= CHAR_AFTER_DP)
return true;
}
dotCheck++;
}
else
return true;
}
// not a valid character
return false;
}
function getKey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input type='number' class='ui-input-text ui-body-a' maxlength='3' id='txtP' step="1" style='text-align:right;width: 50px' name='name1' onkeypress="return restrictChars(event, this)" />
&#13;