Filter input is often used to limit the input of specific data to a text box, or to enter data in a specific format.
When the input that is inseparable from the keyboard, of course, do not open these three events:
KeyDown
KeyPress
KeyUp
Let's take a look at the sequence of these events:
Textbox.addeventlistener ("KeyUp", function " KeyUp " false ); Textbox.addeventlistener ( "KeyDown", function () {Console.log ( "KeyDown" false ); Textbox.addeventlistener ( "KeyPress", function () {Console.log ( "keypress"
false
);
Now that we're filtering something, we need to know what we're pressing.
This can be obtained by charcode in ie9+ Firefox Safari chorme Opera, depending on an attribute in the event object.
In IE8 and lower versions, and opera, this property is not supported, and keycode, regardless of the property value, is included in the event object only when the KeyPress event occurs.
Here's a look at how to get KeyCode or charcode specifically.
functionAddHandler (element,type,handler) {if(Element.addeventlistener) {Element.addeventlistener (Type,handler,false); }Else if(element.attachevent) {element.attachevent ("On" +Type,handler); }Else{element["On" +type] =handler; } } functionGetEvent (event) {returnEvent?event:window.event; } functionGetcharcode (Event) {event=getEvent (event); if(Event.charcode) {Console.log ("Chrome" +Event.charcode); }Else if(Event.keycode) {Console.log ("IE Opera" +Event.keycode); } } varTextBox = Document.forms[0].elements[0];//123AddHandler (textbox, "KeyPress",function(event) {Console.log (Getcharcode (event)); });
The above is mainly compatible with a variety of browsers, mainly for IE, Chrome, Safari, Forfix, Opera
Key (key)-the corresponding ISC code value-converted to the corresponding string form by fromCharCode of the string class
Instance one: Masked characters
var // 123 AddHandler (textbox, "KeyPress",function(event) { = getEvent (event); var code = Getcharcode (event); if (!/\d+/. Test (String.fromCharCode (code))) { preventdefault (event); } });
text Box Script-Filter input