Proprio ieri ho trovato questa funzione qui sul forum e, mi funziona al 100%!!
codice:
<script language='javascript'>
function NumbersOnly(_event, AllowDecimals, AllowNegatives, DecimalDigits) {
var _source = (_event.srcElement)?_event.srcElement:_event.target;
var _sourceText = _source.value;
var keyPressed = _event.keyCode ? _event.keyCode : _event.which ? _event.which : _event.charCode;
var isDigit = (keyPressed > 47 && keyPressed < 58);
if (isDigit) {
if (AllowDecimals) {
var dotPos = _sourceText.indexOf(".");
if (dotPos > -1) {
var caretPosition = (document.selection)?(document.selection.createRange().getBookmark().charCodeAt(2) - 2):_source.selectionStart;
var _DecimalDigits = (DecimalDigits == null)?2:((isNaN(DecimalDigits))?2:DecimalDigits)
if (caretPosition > dotPos)
return ((caretPosition - dotPos) > _DecimalDigits)?false:true;
else
return true;
}
else
return true;
}
else
return true;
}
else {
if (String.fromCharCode(keyPressed) == ".")
if (AllowDecimals)
return (_sourceText.indexOf(".") == -1);
else
return false;
if (String.fromCharCode(keyPressed) == "-") {
if (_sourceText.charAt(0) != "-" && AllowNegatives)
_source.value = "-" + _sourceText;
return false;
}
var AllowedKeys = new Array(0, 8, 9, 13, 27, 46)
for (var i=0; i<AllowedKeys.length; i++)
if (keyPressed == AllowedKeys[i])
return true;
}
return false;
}
</script>
Da richiamare così:
codice:
onKeyPress="return NumbersOnly(event)"