HTML how to enter Tab and LF chars into an input box

Advertisements

I need to let the user input tabs into a text input box without it cycling focus to other elements and also let them enter multi-line strings (LF chars).

Any ideas? I’m trying to make a Whitespace (lang) IDE and so only being able to input one of the three chars needed makes it a bit difficult-

<input type="text" id="main_input">

>Solution :

Do you need an <input> element? It’s by design intended to display a single line of text. For multi-line text, you can use the <textarea> element.

For example:

document.getElementById('mytext').addEventListener('keydown', function(e) {
  if (e.key == 'Tab') {
    e.preventDefault();
    var start = this.selectionStart;
    var end = this.selectionEnd;

    // set textarea value to: text before caret + tab + text after caret
    this.value = this.value.substring(0, start) + "\t" + this.value.substring(end);

    // put caret at right position again
    this.selectionStart = start + 1;
    this.selectionEnd = start + 1;
  }
});
<textarea id="mytext"></textarea>

Leave a ReplyCancel reply