Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic JS: Adding characters at cursor position, while maintaining cursor position

Tags:

javascript

Say I am making a basic Calculator that allows whole expressions to typed by the user. I'll use a simple <input> tag.

The user can type whatever they want, but I want to make it even easier for the client, I want to add a closing parenthesis immediately after they type (, so I set up my javascript to detect when ( is input by into the input field, then += a ) to the input field.

The problem with my code is that it adds the parenthesis to the end of the input, regardless of where they type the parenthesis, even at the beginning.

How can I add a character where ever the cursor is?

My code is as follows:

input = document.querySelector("input[type=text]");

input.addEventListener(`keyup`, (event)=>
{
  if(event.key === `(`)
  {
    input.value+=`)`;
  }
});
<input type="text" placeholder="Put mathematical expression"></input>

1 Answers

I believe that should solve your problem.

let input = document.querySelector("input[type=text]");

input.addEventListener(`keyup`, (event) => {
    if(event.key === '(') {
        let cursorPos = input.selectionStart;
        input.value = input.value.substr(0, cursorPos) + ')' + 
                      input.value.substr(cursorPos);
    }   
});

like image 106
I. Pereira Avatar answered Mar 13 '26 00:03

I. Pereira



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!