Last active
March 14, 2017 15:51
-
-
Save amirkhiz/fbbaad8c31633e6f0a808ef5aaf8712a to your computer and use it in GitHub Desktop.
Get input keypress and filter content before adding to input
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
source