Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: if key "someKey" pressed

Tags:

jquery

keyup

i know that i can detect a key, which has been pressed with the following code:

$('input').keyup(function (e){
if(e.keyCode == 13){
    alert('enter');
  }
})

But i need to know if any key was pressed. pseudocode:

if ($('input').keyup() == true)
  { 
      doNothing();
  }
  else {
      doSomething();
  }

How can I do that?

like image 579
Keith L. Avatar asked Dec 20 '11 10:12

Keith L.


People also ask

How do you check if a specific key is pressed JS?

Using JavaScript In plain JavaScript, you can use the EventTarget. addEventListener() method to listen for keyup event. When it occurs, check the keyCode 's value to see if an Enter key is pressed.

What is e KeyCode === 13?

Keycode 13 is the Enter key.

Do something when key is pressed JavaScript?

There are three different keyboard events in JavaScript: keydown : Keydown happens when the key is pressed down, and auto repeats if the key is pressed down for long. keypress : This event is fired when an alphabetic, numeric, or punctuation key is pressed down. keyup : Keyup happens when the key is released.

What is difference between Keydown and keypress?

The keydown and keyup events provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup , but as 97 by keypress .


1 Answers

Because 'keyup' will be fired when ANY key is pressed, you just leave out the if...

$('input').keyup(function (e){
  // do something
})

Merging this into your current code, you could do something like...

$('input').keyup(function (e){
  alert('a key was press');

  if (e.keyCode == 13) {
      alert('and that key just so happened to be enter');
   }
})
like image 65
isNaN1247 Avatar answered Oct 27 '22 03:10

isNaN1247