Home > Software engineering >  How to autocomplete brackets in HTML textarea?
How to autocomplete brackets in HTML textarea?

Time:10-30

I need to autocomplete brackets in an HTML textarea. For example, if the user types ( in the textarea, the value of the textarea should be () (and it is better if the cursor will be in the middle of the brackets; I also need to know how to do that.)

I tried the following:

let editor = document.getElementById("editor");

editor?.addEventListener("keypress", (ev) => {
    if(ev.key == "(") {
        editor.value  = ")";
    }
});
<textarea id="editor" cols="30" rows="10"></textarea>

This is what I am getting:

enter image description here

This is what I am expecting to get:

enter image description here

CodePudding user response:

Please use snippets to describe your problems, it helps the community to identify the problem quickly and test it without having to reproduce on our own. Here I'm using the "input" event, detecting the last typed character and acting when it is "(". You can move the carret using selectionStart and selectionEnd

const editor = document.getElementById("editor");

editor?.addEventListener("input", e => {
 if (e.data?.length === 1 && e.data === "(") {
   const start = editor.selectionStart;
   const end = editor.selectionEnd;
   editor.value = editor.value.slice(0, start)   ")"   editor.value.slice(start, editor.value.length);
   editor.selectionStart = start;
   editor.selectionEnd = end;
 }
});
<textarea id="editor" cols="30" rows="10"></textarea>

  • Related