Ban apostrophes when entering text in HTML text field

I am looking for a simple, possibly JS, to ban the apostrophe onKeyUp or OnKeyPress. For example, every time a user presses a key, if it was an apostrophe (Jame Pizza), replace it with a space. I do not want to process it in PHP
I found the code, but it binds JS to a text field that I don't want. I need something global

+4
source share
2 answers

It is always better to prevent keystrokes than back deletion. To do this, you need to catch the keypress event ( keyup too late):

 document.getElementById('yourTextBoxID').onkeypress = function () { if (event.keyCode === 39) { // apostrophe // prevent the keypress return false; } };​ 

http://jsfiddle.net/TSB9r/

If you want to stop displaying ' in the field, but want the keypress event to be passed to the parent elements, replace return false; on event.preventDefault(); . (suggested by Eivind Eidheim Elseth in the comments)

+7
source

Below you will find the features. It captures all input elements on the page and assigns keydown and keyup event handlers to each of them. If they find an apostrophe, it will call the preventDefault() method ..

 function listen(event, elem, func) { if (elem.addEventListener) return elem.addEventListener(event, func, false); else elem.attachEvent('on' + event, func); } listen('load', window, function() { var inputs = document.getElementsByTagName('input'); for (var i = 0; i < inputs.length; i += 1) { keyHandler(i); } function keyHandler(i) { listen('keydown', inputs[i], function(e) { if (e.keyCode === 222) { // 222 is the keyCode for apostrophe e.preventDefault(); } }); listen('keyup', inputs[i], function(e) { if (e.keyCode === 222) { // 222 is the keyCode for apostrophe e.preventDefault(); } }); } }); 
0
source

All Articles