我有以下 javascript 代码适用于帮助将文本输入限制为单个小数点,已上传到我的测试服务器cogwheelmedia.net/Survey/numerickey.php
虽然它适用于 Safari,但它似乎不适用于 Firefox。我需要进行哪些更改才能使其在所有浏览器中运行?
<body>
<p>
<script type="text/javascript">
function OnTextNumericKeyPress(evt) {
var theEvent = evt || window.event;
var rv = true;
var key = (typeof theEvent.which === 'undefined') ? theEvent.keyCode : theEvent.which;
if (key && (key !== 8)) {
var keychar = String.fromCharCode(key);
var keycheck = /[.0-9]/;
if (!keycheck.test(keychar) || (keychar == '.' && evt.srcElement.value.indexOf('.') > -1)) {
rv = theEvent.returnValue = false; //for IE
if (theEvent.preventDefault) theEvent.preventDefault(); //Firefox
} else {
var number = evt.srcElement.value.split('.');
if (number.length == 2 && number[1].length > 1) {
rv = theEvent.returnValue = false; //for IE
if (theEvent.preventDefault) theEvent.preventDefault(); //Firefox
}
}
return rv;
}
function ValidateDecimal(o) {
if (o.value.length > 0) {
var objReg = /^\d+(\.\d{1,2})?$/;
if (objReg.test(o.value))
o.style.backgroundColor='';
else
o.style.backgroundColor='red';
return false;
}
}
}
</script>
<input name="txtPrice" ID="txtPrice" type="text" runat="server" MaxLength="8" onfocusout="return OnTextNumericKeyPress(event);" onBlur="return OnTextNumericKeyPress(event);" onKeyPress="return OnTextNumericKeyPress(event);" onkeyup="ValidateDecimal(this);"/>
</p>
</body>
</html>