0

I was trying to call a function on the press of the shift + enter key.

What I was trying is this

$('.o_searchview_input').on('keydown', function(event) {
debugger;
  if (event.keyCode == 13 && !event.shiftKey) {
    $(this).trigger(jQuery.Event("keydown", {
      keyCode: 13, // ENTER
      shiftKey: true
    }));
  } else if (event.keyCode == 13 && event.shiftKey) {
    console.log('shift + enter');
  }
});

But it is pressing the shift key automatically.

I am worried is there any option in JavaScript to trigger an even on the press of two keys?

  • Does this answer your question? [How to detect keyboard modifier (Ctrl or Shift) through JavaScript](https://stackoverflow.com/questions/13539493/how-to-detect-keyboard-modifier-ctrl-or-shift-through-javascript) also see: [KeyboardEvent.getModifierState()](https://stackoverflow.com/questions/13539493/how-to-detect-keyboard-modifier-ctrl-or-shift-through-javascript) – pilchard Jun 02 '21 at 12:48
  • You can check this https://stackoverflow.com/questions/6014702/how-do-i-detect-shiftenter-and-generate-a-new-line-in-textarea – RGA Jun 02 '21 at 12:58

2 Answers2

2

There is no event that checks if multiple keys are pressed. If you want to check for 2 keys you will need to create keydown and keyup events to track which keys are pressed but not released manually.

The exception to this rule is Shift Alt and Ctrl/Cmd These are known as key modifiers and can be used like in your example:

if (event.keyCode == 13 && event.shiftKey) // do something

dehart
  • 1,554
  • 15
  • 18
0

Using event.preventDefault() on shift + enter does the job for you

$('.o_searchview_input').on('keydown', function(event) {
  if (event.keyCode == 13 && event.shiftKey) {
    event.preventDefault(); // prevent default action
    console.log('shift + enter');
    // call your function
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

`Enter` adds new line, Where as `Shift + Enter` is prevented
<textarea class="o_searchview_input"></textarea>
Wazeed
  • 1,230
  • 1
  • 8
  • 9