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

How to autocomplete brackets in HTML textarea?

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:

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

enter image description here

This is what I am expecting to get:

enter image description here

>Solution :

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 === "(") {
   editor.value += ")";
   editor.selectionStart = editor.value.length - 1;
   editor.selectionEnd = editor.value.length - 1;
 }
});
<textarea id="editor" cols="30" rows="10"></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