I_love_vegetables
I_love_vegetables

Reputation: 1341

why cant i delete a character in the input field

im creating a function to automatically add a ] when the user presses [ on the input field which works perfectly

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

function add(){
  if(input.value === "["){
  input.value = "[]";
  }
}
<input id="input" oninput="add()">

but after i input [ and the input value becomes [], i cant press the backspace key to delete the "]" and i have to use delete key to delete it from the back, why is it so?

Upvotes: -1

Views: 1097

Answers (2)

muzzletov
muzzletov

Reputation: 688

Because writing "[" can't be distinguished from deleting "]" where the resulting input value evaluates to "[" .

To find out if a character has been deleted, add the event as a parameter to add

function add(event) ...

and check if event.data equals to "null".

function add(event) {
 if(event.data == null) return;
 // the rest of your code
}

and add the event parameter to oninput:

<... oninput="add(event)"> ...

Upvotes: 0

Stairss
Stairss

Reputation: 176

It's a really common problem to solve, there was a post before about this, but solution for your problem should look like this:

const brackets = new Map([
  ['{', '}'],
  ['[', ']'],
  ['(', ')']
]);
    
const input =document.querySelector('.input');

input.addEventListener('input', (e) => {
    const origin = e.target;
    const pos = origin.selectionStart;
    const val = [...origin.value];
    
    const char = val.slice(pos-1, pos)[0];
    const bracket = brackets.get(char);
    
    if (bracket) {
      val.splice(pos, 0, bracket);
      origin.value = val.join('');
      origin.selectionEnd = pos;
    }
});
<input class="input">

Feel free to ask if you don't understand something :)

Upvotes: 1

Related Questions