Js in the input box to block the key can only type a number of sample code

  • 2020-03-30 01:14:05
  • OfStack

<script language="javascript">
function GetInput(){//Mask non - numeric and non - backspace characters
    var k = event.keyCode;   //48-57 is the number key for the large keyboard, 96-105 is the number key for the small keyboard, and 8 is the backspace symbol  please 
    if ((k <= 57 && k >= 48) || (k <= 105 && k >= 96) || (k== 8)){
     return true;
    } else {
     return false;
function Set(obj){
   //Immediate processing of the contents of the input box, such as performing certain operations
<input type='text' value='1' onkeydown='return GetInput()' onkeyup='Set(this)' >

Technical essentials: The onkeydown event is triggered before the onkeyup event. When the onkeydown event returns false, the onkeyup event will not be triggered, and the character that the user just pressed will not be in the input box, thus achieving the purpose of masking some characters. Understanding this event trigger mechanism should be extended in the mind (for example, several events of the mouse will be the same mechanism)...

Related articles: