Search code examples
javascriptjqueryinputkeypress

Prevent spaces in input field on keypress event


I'm using the following code to detect multiple keys on a keypress event:

var down = [];
$(document).keydown(function (e) {
     down[e.keyCode] = true;
}).keyup(function (e) {
     if (down[17] && down[32]) {
          // Do something
     }
     down[e.keyCode] = false;
});

However, this hotkey (CTRL + SPACE) is meant to be used while an input field has focus. So whenever I press the key combination, it also adds a space to the input field.

How can I prevent this from happening? I've looked at ways to disable spaces in input (like this), but I can't figure out how to make it work inside my keypress event only.


Solution

  • I ended up using a different approach, as MelanciaUK suggested.

    On the keyup event, it removes the last character in the input field.

    var down = [];
    $(document).keydown(function (e) {
         down[e.keyCode] = true;
    }).keyup(function (e) {
         if (down[17] && down[32]) {
              // Do something
              input = $(':focus');
              input.val(function (index, value) {
                   return value.substr(0, value.length - 1);
              });
         }
         down[e.keyCode] = false;
    });
    

    While it doesn't prevent the space from being added, it removes it immediately.