python38292
python38292

Reputation: 69

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.

Upvotes: 2

Views: 5268

Answers (2)

Sheraff
Sheraff

Reputation: 6682

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".

Upvotes: 3

Ivan Frolov
Ivan Frolov

Reputation: 103

Add keydown event listener and prevent default behavior on some specific cases:

input.addEventListener("keydown", function (e) {
    if (e.key === 'd') {
        e.preventDefault()
    }
});

This will prevent 'd' from input

Upvotes: 1

Related Questions