Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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">

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading