简体   繁体   中英

Javascript keypress event not functioning in Firefox

Here is my code:

function filter(obj,re) {
      if (obj&&obj.tagName.toLowerCase()=="input") {
        obj.filter=re;
        on(obj,"keypress",function(e) {
          if (e.keyCode<32) return true;
          if (!(String.fromCharCode(e.keyCode).match(this.filter))) {
            e.stopPropagation(); e.preventDefault(); return false;
          }
        });
      }
    }

filter(element,new RegExp('[\\w\\d]+'));

It's working fine in google chrome but it doesn't work in firefox. What occurs is I add the dom element a keypress event that filters out the data based on the filter.

In any case, any help would be appreciated.

UPDATE

Here is the on function:

function on(obj,evt,func) { 
   if (obj.addEventListener) obj.addEventListener(evt,func,false); 
   else obj.attachEvent("on"+evt,func); 
}

The KeyboardEvent.keyCode property is deprecated - in Firefox all printable characters result in a zero value and thus your handler is always returning without doing anything. The charCode property still appears to work in both Chrome and Firefox however you shouldn't rely on this as in actual fact all of the character code properties are either deprecated or non-standard.

As noted on MDN:

This shouldn't be used by new web applications. IE and Firefox already (partially) support KeyboardEvent.key. Also, Google Chrome and Safari support KeyboardEvent.keyIdentifier which is defined in the old draft of DOM Level 3 Events. If you can use them or one of them, you should use them/it as far as possible.

Note: Web developers shouldn't use the keycode attribute for printable characters when handling keydown and keyup events. As described above, the keycode attribute is not useful for printable characters, especially those input with the Shift or Alt key pressed.

If you are targeting modern browsers or devices then the key property is intended to hold the value of the pressed key however this option is still quite new and not cross-browser.


For cross-browser / legacy support, what most people do is validate the the entire input instead of just one key. For instance, the following simplistic example lets the user type but then strips the characters from the value string which don't match the regular expression.

<input id="myInput"/>
var input = document.getElementById('myInput'),
    sanitise = function(){
        input.value = input.value.replace(/\w+/, '');
    };

input.addEventListener('keyup', sanitise);

» Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM