最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Jquery keypress except: {something} - Stack Overflow

programmeradmin2浏览0评论

Is there any shortcut( actually a function) in jQuery or Javascript to handle button press except something, or only something, e.g.:

$(input).keypress('nonfunctional' function(){ 
  // do something
});

that will trigger only on [a-z][0-9] buttons pressed and ignoring single shift or ctrl but handling shift+a => A pressed?

P.S.i do know about if(key.code == 123) then ...

Is there any shortcut( actually a function) in jQuery or Javascript to handle button press except something, or only something, e.g.:

$(input).keypress('nonfunctional' function(){ 
  // do something
});

that will trigger only on [a-z][0-9] buttons pressed and ignoring single shift or ctrl but handling shift+a => A pressed?

P.S.i do know about if(key.code == 123) then ...

Share Improve this question asked Jan 22, 2013 at 13:39 tedted 1871 silver badge7 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 10

No, if you want to exclude specific keys that's what the event.keyCode / event.which properties are there for.

Or you can extend jquery keypress. Something like this I guess:

$.fn.keypressBut = function(codes, callback) {
    $(this).keypress(function(e) {
        ~$.inArray(e.keyCode, codes) || callback.call(this, e);
    });
}

// Lets ignore Enter and Space
$('input').keypressBut([13, 32], function(e) {
    alert(e.keyCode);
})

You could do something like

  1. Extend jquerys fn propertie with a function which takes params like

    • Some Data
    • A callback function
  2. Write a validation Function which

    • Converts the keyCode to a String
    • Match it against a Regular Expression.
    • If the shiftKey was Pressed
      • Convert it to Upper Case
    • Check if other Conditions, like Ctrl/Alt key Pressed are met.
    • Returns the Result.
  3. If the validation succeeds
    • execute the callback function

On the code site this could like

  $.fn.selectedKey = function (cb, data) {
      def.call(data, {
          ctrlKey: 2, //0: musn't be pressed, 1: must be pressed, 2: both.
          altKey: 2, // "
          invert: 0, //inverts the filter
          filter: /.*/, // A Regular Expression, or a String with a Regular Expression
          preventDefault: false //Set to true to prevent Default.
      }); //Sets the default Data for the values used,

      function validate(e) {
          var key = e.char = String.fromCharCode(e.keyCode || e.which); // Converts the pressed key to a String
          if (e.shiftKey) key = key.toUpperCase(); //Handles Case Sensitivity.
          var exp = new RegExp(e.data.filter.replace(/\\\\(\d)/g, String.fromCharCode("$1"))); //Creates a new RegExp from a String to e.g. allow "\2" to match the keyCode 2
          var c = !! (e.data.ctrlKey ^ e.ctrlKey ^ 1 > 0); //c == true if the above stated conditions are met e.g Ctrl Key Pressed and `ctrlKey == 1` -> true
          var a = !! (e.data.altKey ^ e.altKey ^ 1 > 0); //e.g Alt Key Pressed and `altKey == 0` -> false
          return (exp.test(key) && (c && a)); //Returns the validation Result
      }

      function def(obj) { //a minimal helper for default values
          for (var prop in obj) {
              this[prop] = this[prop] || obj[prop];
          }
      }
      this.keypress(data, function (e) {
          if (e.data.preventDefault) e.preventDefault();
          if (validate(e) != e.data.invert) cb(e); //Calls the callback function if the conditions are met
      });
  };

Which you could then use the following ways

With a regex

  $("body").selectedKey(function (e) {
      console.log("All lower characters Numbers and 'A': " + e.char);
  }, {
      filter: /[a-z]|[0-9]|A/,
      ctrlKey: 2,
      altKey: 2
  });

This would be triggered if any [a-z] or [0-9] or the Shift key + A has been pressed, regardless of the state of ctrl and alt

Or a keycode

  $("body").selectedKey(function (e) {
      // do somet
      console.log("KeyCode 2 " + e.char);
  }, {
      filter: "\\2", //Ctrl + b
      ctrlKey: 1,
      altKey: 2
  });

Would be triggered if you press ctrl +b

You could also bine those both.

Heres an Example on JSBin, to fiddle around with.

There is a jQuery plugin for using classes and regex for filtering keypresses if you dont want to write a large if statement to detect the key code pressed, its called keyfilter. An example would be

$(selector).keyfilter(/[a-z]/);

For example this function below allow only numbers en handle this functions using the keydown event.

function OnlyNumbers(event) {
    if (event.keyCode == 46 || event.keyCode == 8 || event.keyCode == 9 || event.keyCode == 27 || event.keyCode == 13 || (event.keyCode == 65 && event.ctrlKey === true) || (event.keyCode >= 35 && event.keyCode <= 39)) { return; }
    else { if (event.shiftKey || (event.keyCode < 48 || event.keyCode > 57) && (event.keyCode < 96 || event.keyCode > 105)) { event.preventDefault(); } }
}

have you tried event.altKey/event.shiftKey/event.ctrlKey ??

发布评论

评论列表(0)

  1. 暂无评论