Online to find a lot of code, basically the same effect, that is, when you enter the negative sign, it will be all the contents of all empty, this effect on the user's experience is very bad. In case, the user accidentally lost the wrong, and then have to re-enter all over again.
I ended up going to the internet and referencing a lot of knowledge about input box events, and finally put together an optimal way to handle disallowing negative numbers, so feel free to like and comment.
Code:
<input type="number" onkeypress="return noNumbers(event)" />
-
function noNumbers(e){
-
var keycode = window.event ? e.keyCode : e.which;
-
The //Internet Explorer/Chrome browsers use to retrieve pressed characters, while Netscape/Firefox/Opera etc. use .
-
var keychar = String.fromCharCode(keycode);//fromCharCode: convert Unicode code to a character.
-
-
if(keycode >= 48 && keycode <= 57){ // Numeric keypad code: 0-9
-
e.returnValue = true
-
}else if(keycode >=96 && keycode <= 105){ //onkeydown event: keypad number code: 0-9
-
e.returnValue = true;
-
}else if(keycode == 8 || keycode == 46){ // Delete key and delete
-
e.returnValue = true;
-
}else if(keycode == 45){ //Negative signs are not allowed. onkeydown event:keycode == 109 || keycode == 189
-
e.returnValue = false;
-
}else{ //Other characters are not allowed
-
e.returnValue = false;
-
}
-
}
'
(of a computer) run
Relevant knowledge:
Online effect: Entering a negative sign sets everything to empty.
-
<input type="number" onkeyup="checkNum(this)" >
-
function checkNum(obj){
-
obj.value=obj.value.replace(/[^\-\d]/g,'');
-
if(obj.value.indexOf('-')>=0){
-
obj.value='-'+obj.value.replace(/-/g,'');
-
}
-
}
Note: No special needs, do not use the onkeydown event, onkeydown triggered by the state code is not consistent, the English above the number and the number of the keypad on behalf of the code is not the same. onkeypress to get the value of the ASCII, the code of the onkeydown is a virtual code! The usual operation is ASCII.