Johnny Johnny - 2 months ago 18
Javascript Question

How to return an input field back to its default behaviors?

I'm working on a site that prevents backspace in an input field by default, but for this particular input, I would like to return it to its default behaviors to accept backspace.

What is the simplest way to do this? Basically I need the opposite of preventDefault().

Update: I added the following message in the comment but thought it's important to the question. So here it is:

Unfortunately, I have no idea how it prevents the backspace. I'm creating a chrome extension which injects an input field into the page. Everything works except the backspace. I tried to find the code where it prevents it but it's impossible.

My code to create the field is this:

if(!document.getElementById("input_typing")){
var input = document.createElement('input');
input.id = "input_typing";
input.tabIndex = 1;
input.style.width = "95%";
input.focus();
txts[i].parentNode.appendChild(input);
}

Answer

My idea is: there could be an handler attached to the document so that *site that prevents backspace *.

I'm not sure of this, but I created a snippet to clarify my idea:

if an event handler prevent the default action on backspace you may add a new event handler for your newly created input field in order to stop propagation.

//
// Let's assume this is the site handler to prevent backspace
//
document.addEventListener('keydown', function(e) {
  if (e.which === 8) {
    e.preventDefault();
  }
});


//
// your new element
//
if(!document.getElementById("input_typing")){
  var input = document.createElement('input');
  input.id = "input_typing";
  input.tabIndex = 1;
  input.style.width = "95%";
  input.focus();
  document.querySelectorAll('input[type="text"]')[0].parentNode.appendChild(input);

  //
  // Add the keydown event handler to stop propagation
  //
  input.addEventListener('keydown', function(e) {
    e.stopPropagation();
  });
}
<form action="action_page.php">
    First name:<br>
    <input type="text" name="firstname" value="Mickey">
    <br>
    Last name:<br>
    <input type="text" name="lastname" value="Mouse">
    <br><br>
    <input type="submit" value="Submit">
</form>