Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to autoclose paranthesis in javascript input

const closeChars = new Map([
  ['{', '}'],
  ['[', ']'],
  ['(', ')']
]);
    
maintextarea=document.getElementById('maintextarea');

maintextarea.addEventListener('input', function (e) {

    const pos = e.target.selectionStart;
    const val = [...e.target.value];
    
    const char = val.slice(pos-1, pos)[0];
    const closeChar = closeChars.get(char);
    
    if (closeChar) {
      val.splice(pos, 0, closeChar);
      e.target.value = val.join('');
      e.target.selectionEnd = pos;
    }
});
Source by stackoverflow.com #
 
PREVIOUS NEXT
Tagged: #autoclose #paranthesis #javascript #input
ADD COMMENT
Topic
Name
4+5 =