Martin AJ Martin AJ - 2 months ago 9
Javascript Question

How can I check has the input been empty?

Here is my code:



$("input").on('keyup', function(ev){
if(/(8)/.test(ev.which) && this.value == ''){
alert('when you pressed backspace, the input was empty already');
}
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />





All I'm trying to do is implementing this:


when you pressed "backspace", the input was empty already


Actually I don't know English very well, maybe the correct sentence is this:


when you pressed "backspace", the input has been empty before your pressing


Ok, write a character into the input, then press backspace, what happens? Both that character will be removed and that alert will be shown. I need to set one step between them, I mean I need two separated backspace for those events.

One backspace for removing the last character, one backspace else for showing that alert. How can I do that?

Answer

The event that you are looking for is keydown

  $("input").on('keydown', function(ev){
      if(ev.which === 8 && this.value == ''){
        alert('when you pressed backspace, the input was empty already');
      }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />

UPDATE You can handle it with class as well:

  $("input").on('keyup', function(ev){
      if(ev.which === 8 && this.value == '' && $(this).hasClass('empty-input')){
        $(this).removeClass('empty-input');
        alert('when you pressed backspace, the input was empty already');
      } else {
        if (this.value == '') {
          $(this).addClass('empty-input');
        }
      }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" />