This article mainly introduces js characters used to filter non-numeric characters in the input box. It is very simple but practical. For more information, see HTML:
The Code is as follows:
JS:
Window. onload = function (e) {var text = document. getElementById ("only"), pattern =/\ d/, // pattern matches the alphanumeric key pattern2 =/(9 [6-9]) | (10 [0-5]) | 3 (7 | 9) // pattern2 matches the numeric key on the keypad and the left and right direction keys EventHandle = {}, event = e | window. event; // an event processing object // when a webpage is loaded, judge and define properties for the event processing object. In this way, the event object method only needs to be judged once, other events in the future // The if (event. preventDefault) {EventHandle. preventDefault = function (e) {e. preventDefault () ;};} else {EventHandle. preventDefault = fu Nction (e) {e. returnValue = false;} text. onkeydown = function (e) {var event = e | window. event; // The event objects of different events are different. The event is not the same as the previous event. if (! Pattern. test (String. fromCharCode (event. keyCode) & event. keyCode! = 8 // keyCode = 8 is the return key. Because you can modify the entered number, the Return key and the left and right direction keys are not allowed &&! Pattern2.test (event. keyCode. toString () | event. shiftKey | event. ctrlKey | event. metaKey) {EventHandle. preventDefault (event); // if this method of the object is not used, it can be executed as follows. However, it is unnecessary to make a judgment every time you press the keyboard, therefore, when the page is loaded, define a method for the event processing object. After loading, the object method is determined and will be ready later. // if (event. preventDefault) {// event. preventDefault (); //} else {// event. returnValue = false ;//}}}}
Uncommented version:
window.onload=function(e){var text=document.getElementById("only"),pattern=/\d/,pattern2=/(9[6-9])|(10[0-5])|3(7|9)/,EventHandle={},event=e||window.event;if(event.preventDefault){EventHandle.preventDefault=function(e){e.preventDefault();};}else{EventHandle.preventDefault=function(e){e.returnValue=false;}}text.onkeydown=function(e){var event=e||window.event;if(!pattern.test(String.fromCharCode(event.keyCode))&&event.keyCode!=8&&!pattern2.test(event.keyCode.toString())||event.shiftKey||event.ctrlKey||event.metaKey){EventHandle.preventDefault(event);}}}
In IE11, F12 can open the developer tool and select the IE version for debugging.