I am trying to limit keyboard input in my text field to numbers [0-9]
and the minus sign -
only (no copy/paste, etc.) and the delete key obviously.
The code works for limiting to numbers and the delete key but it doesn't work for the minus sign -
part.
The user should only be able to enter a minus sign -
in front of their number, if they try to enter 1
then -
it should not input the -
but right now the -
part doesn't work at all.
Fiddle: http://jsfiddle.net/7XLqQ/1/
I think this piece of code is the issue but it looks fine. It checks that the text input is blank and if so it input the minus sign -
.
// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
return true;
}
My full code:
<input type="text" maxlength="10" id="myInput">
<script>
var input = document.getElementById("myInput");
input.onkeypress = function(e) {
var unicode = e.keyCode;
if (unicode == 49 || unicode == 50 || unicode == 51 || unicode == 52 || unicode == 53 || unicode == 54 || unicode == 55 || unicode == 56 || unicode == 57 || unicode == 48) {
return true;
} else {
return false;
}
// Only enter the minus sign (-) if the user enters it first
if (unicode == 45 && input.value == "") {
return true;
}
};
</script>