Skip to content
Advertisement

Stop characters being typed into form

I have this jQuery which stops the enter key from being pressed and I have prepared it to accept an array of disallowed keypresses..

    $('.form input').bind('keypress', function(e) {
        var keys = [13];
        for (var i = keys.length; i--;){
            if(e.keyCode===keys[i]){
                return false;
            }
        }
    });

I want to do similar thing with the | character, but since it is shift of 220 and I don’t need to stop from being entered into the form, how do I restrict that character or use a modifier key? (will also be processing it out server-side, of course).

I’m also aware that keyboard layout for special characters may differ from keyboard to keyboard with different localization, so it may be necessary to focus on the resulting character rather than the key itself (not entirely sure on that), but I don’t want to introduce a large amount of overhead

Advertisement

Answer

The keypress event is about characters, not keys. You can just compare keyCode to the character code for "|" ("|".charCodeAt(0)) directly, no need to worry about the shift key being down (and it may not be on all keyboards).

Example – live copy | source:

HTML:

<p>Try to type | in the box below.</p>
<input id="theInput" type="text" size="80">

JavaScript:

jQuery(function($) {

  var keys = [13, "|".charCodeAt(0)];
  $("#theInput").keypress(function(e) {
    var index;

    for (index = 0; index < keys.length; ++index) {
      if (keys[index] === e.keyCode) {
        display("Denied!");
        return false;
      }
    }
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});

Or as bažmegakapa points out, since you’re already using jQuery, you can use its inArray function:

jQuery(function($) {

  var keys = [13, "|".charCodeAt(0)];
  $("#theInput").keypress(function(e) {
    if ($.inArray(e.keyCode, keys) !== -1) {
      display("Denied!");
      return false;
    }
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }
});
Advertisement