Brandon Brandon - 2 months ago 5x
HTML Question

How might I simulate a backspace action in a text field?

When a button is pressed, I simply want to simulate a "backspace" in a regular text box, deleting the character to the left of the cursor.

Google and various forums are producing really random results on this. What's the proper way to do this?


So I'm guessing that you don't mean to put focus on the text input to delete it.

There is a couple of methods you could try. First, get the current contents of the input and remove the last character, then put the modified string back in the text field. For example (this code should work)

var txt = $('#myinputtextbox');
txt.val( txt.val().slice(0,-1) );

The other would be to use js to simulate the backspace character key being hit. You would need to focus on the input, move the cursor to the end of the line, and then trigger the character.