31

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,438
  • 68
  • 55
  • 126
rsk82
  • 26,257
  • 48
  • 141
  • 229

4 Answers4

43

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
  • 14,571
  • 4
  • 38
  • 49
2
element.onkeydown = function(o) {
  o = o || event;
  if (o.shiftKey && o.keyCode == 13) {
    /* shift + enter pressed */
  }
}
ic3b3rg
  • 14,063
  • 4
  • 25
  • 49
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,805
  • 6
  • 41
  • 75
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,010
  • 16
  • 13