Avoid deleting entire input value on backspace

856 Views Asked by At

I have an input field which is deleting all the words its contains when I'm pressing backspace key.

I tried to implement a small code to delete the words letter by letter but I'm getting an error: selectInput.substring is not a function.

let selectInput = document.querySelector('#searchedWord');

selectInput.addEventListener("keydown", function(e) {
const key = e.key;
 if (key === "Backspace") {
   selectInput.value = selectInput.substring(0, selectInput.length -1);
   // other code to be exectuded below
 }
});

What am I missing?

1

There are 1 best solutions below

1
Steini On

"selectInput" is NOT a string in your context its a DOM-object (or DOM-tree [=array] if multiple elements have been found but since you used an ID "#"searchedWord we should be fine here)

you must access ".value" attribute

Try:

selectInput.value = selectInput.value.substring(0, selectInput.length -1)

You basically already did it right where you assigned it into. :D