Reputation: 74
I am looking for a simple maybe JS to forbid apostrophe onKeyUp or OnKeyPress kind of thing. For ex, every time user presses a key if it was apostrophe (Jame's Pizza) replace it with space. I don't want to process it in PHP
I found a code but it ties the JS to the textfield Name which I don't want. I need something global,
Upvotes: 4
Views: 4292
Reputation: 46647
It's always better to prevent the keystroke than to retroactively delete it. To accomplish this, you need to intercept the keypress
event (keyup
is too late):
document.getElementById('yourTextBoxID').onkeypress = function () {
if (event.keyCode === 39) { // apostrophe
// prevent the keypress
return false;
}
};
If you only want to stop the '
from appearing in the box but would like the keypress event to propagate to parent elements, replace the return false;
with event.preventDefault();
. (suggested by Eivind Eidheim Elseth in the comments)
Upvotes: 7
Reputation: 2751
Please find below functions. It grabs all of the input
elements on the page and assigns keydown
and keyup
event handlers to each of them. If they detect 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();
}
});
}
});
Upvotes: 0