Search code examples
javascriptinputonkeyup

Delete last character entered in input - Javascript


i have the following input:

<input id="myInput" type='text' onkeyup="validate(this)" />

And in my .js file I have:

var input = document.getElementById("myInput");

input.addEventListener("keyup", function (e) {
    console.log(e.key);

});

function validate(characters) {
    console.log(characters.value);
}

My question is: can I delete the e.key corresponding to the last character typed.

Note:

Deleting the last character of characters is not a solution, since the character can be placed in any position.


Solution

  • You could do it based on the caret's position

    const input = document.querySelector('input')
    
    input.addEventListener("keyup", e => {
      const position = e.target.selectionStart
      input.value = input.value.substring(0, position-1) + input.value.substring(position+1)
    })
    <input type="text"/>

    Or you could track changes

    const input = document.querySelector('input')
    
    let previousValue = input.value
    input.addEventListener("keyup", e => {
      // if it matches your condition
      input.value = previousValue
    
      // reassign so that it works again next time
      previousValue = input.value
    })
    <input type="text"/>

    Of course, you'd want to add conditions to these otherwise you can't type at all in your input. And check which keys are pressed because some don't add characters (or even remove some). You might want to look at the "change" event instead of the "keyup".