32

I'm doing it for texarea. A function should be called when the user press Enter, but nothing should be done when Shift + Enter be pressed.

I try to simulate here a feature that many IM communicators have: sending a message on Enter but also adding multiple lines using Shift + Enter.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
rsk82
  • 28,217
  • 50
  • 150
  • 240

4 Answers4

44

Test for the enter keycode (13) and if shift key was pressed.

...onkeyup = function(e) {
    if (e.keyCode == 13)
    {
//      if (e.shiftKey === true)
        if (e.shiftKey)  // thruthy
        {
            // new line
        }
        else
        {
            // run your function
        }
        return false;
    }
}

Edit: Accept all truthy values of e.shiftKey

aorcsik
  • 15,271
  • 5
  • 39
  • 49
2
element.onkeydown = function(o) {
  o = o || event;
  if (o.shiftKey && o.keyCode == 13) {
    /* shift + enter pressed */
  }
}
ic3b3rg
  • 14,629
  • 4
  • 30
  • 53
1

I believe you need a keydown event as well to check for the SHIFT key, http://www.quirksmode.org/js/keys.html

nickytonline
  • 6,855
  • 6
  • 42
  • 76
0

Look at the shiftKey property of the event object which will tell you if shift was held while the key was pressed.

ADW
  • 4,030
  • 17
  • 13