admin管理员组

文章数量:1410697

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,

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,

Share Improve this question asked Aug 17, 2012 at 14:58 Clipper 20Clipper 20 741 silver badge8 bronze badges 2
  • Show us the code you found, we can help you to adapt it. What do you mean by "something global"? – Bergi Commented Aug 17, 2012 at 15:03
  • "I don't want to process it in PHP." You're going to need to process it in PHP as well since you can't trust user input. – Mike Samuel Commented Aug 17, 2012 at 15:11
Add a ment  | 

2 Answers 2

Reset to default 7

It's always better to prevent the keystroke than to retroactively delete it. To acplish 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;
    }
};​

http://jsfiddle/TSB9r/

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 ments)

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();
      }
    });
  }
});

本文标签: javascriptForbidding Apostrophe while typing in HTML textBoxStack Overflow