Skip to content

Instantly share code, notes, and snippets.

@amirkhiz
Last active March 14, 2017 15:51
Show Gist options
  • Save amirkhiz/fbbaad8c31633e6f0a808ef5aaf8712a to your computer and use it in GitHub Desktop.
Save amirkhiz/fbbaad8c31633e6f0a808ef5aaf8712a to your computer and use it in GitHub Desktop.
Get input keypress and filter content before adding to input
init();
var pattern = /[A-Za-z0-9-\.]/i;
function inputDigitsOnly(e) {
var chrTyped, chrCode = 0, evt = e ? e : event;
if (evt.charCode != null) chrCode = evt.charCode;
else if (evt.which != null) chrCode = evt.which;
else if (evt.keyCode != null) chrCode = evt.keyCode;
if (chrCode == 0) chrTyped = 'SPECIAL KEY';
else chrTyped = String.fromCharCode(chrCode);
//[test only:] display chrTyped on the status bar
self.status = 'inputDigitsOnly: chrTyped = ' + chrTyped;
//Digits, special keys & backspace [\b] work as usual:
if (chrTyped.match(pattern)) return true;
if (evt.altKey || evt.ctrlKey || chrCode < 28) return true;
//Any other input? Prevent the default response:
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
function addEventHandler(elem, eventType, handler) {
if (elem.addEventListener) elem.addEventListener(eventType, handler, false);
else if (elem.attachEvent) elem.attachEvent('on' + eventType, handler);
else return false;
return true;
}
function init() {
addEventHandler(self.document.getElementById('site-name'), 'keypress', inputDigitsOnly);
}
@amirkhiz
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment