Iuri Siva
Iuri Siva

Reputation: 29

How to set listeners to "backspace press" event in Javascript or Jquery?

I have a button that is enabled or disabled if, respectively, there is or is not text inside an input, as shown in the code snippet below:

var input = document.getElementById('myInput');
var btn = document.getElementById('myButton');

$(input).on('keyup', function(){
  if((input.value != null) && (input.value != ''))
    $(btn).removeClass('btnDisabled');
  else
    $(btn).addClass('btnDisabled');
});

Using keyup event it is working good in my aplication on an smarthphone with Android 6.0.1. But for some reason, on an tablet with Android 4.4.2 if backspace key are pressed till the begin of input, erasing all the text value, the button is still enabled. I researched this problem but I'm still not sure if the WebView version interferes with this. I think so.

I used other code snippets to see if the event is triggered by the "backspace" button, as shown below:

  $(input).on('keydown', function(event){ //I tried keyup, keydown and keypress
      var key = event.keyCode || event.charCode;

      console.log("keydown " + key, "length " + input.value.length);
      //if(key == 8 && input.value.length == 1) $(btn).addClass('btnDisabled');
    });

With this test I saw that the backspace does not trigger the event and the variable key is always equal to 0.

I need to disable the button when input is empty. Where am I going wrong?

Right now, I thank those who help! :D

Upvotes: 0

Views: 269

Answers (1)

fdomn-m
fdomn-m

Reputation: 28621

There is another event that you can use: input

https://developer.mozilla.org/en-US/docs/Web/Events/input

The DOM input event is fired synchronously when the value of an <input>, <select>, or <textarea> element is changed.

In this case, change

$(input).on('keydown', 

to

$(input).on('input', 

See also: https://caniuse.com/#search=input

Upvotes: 1

Related Questions