0

SUPER LASY: How to add "\n" to an <input>'s value on Ctrl+Enter?


TL;DR: Using JavaScript, DOM and KeyboardEvent (and something else maybe), how to detect specific keyboard combination and substitute it with custom character?


I have a simple #input element on the page.
What I need is to achieve a behaviour, when input.value is being updated by whatever character user is typing, unless it is a specific predefined combination (i.e. Ctrl+Enter).
If so, add a specific predefined character (i.e. "\n") to input.value.

The intuitive way to do this will not work properly:

input.onkeydown = function(event) {
    if (event.keyCode === 13 && event.ctrlKey)
        input.value += "\n";
}

... because it will add "\n" always at the end of the value, despite the position of a caret.

So, how do I do that?

Dima Parzhitsky
  • 6,233
  • 3
  • 24
  • 53

0 Answers0