如何检查输入是否为空?

时间:2016-09-21 20:40:54

标签: javascript jquery

这是我的代码:

  $("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" />

我要做的就是实现这个:

  

当你按下“退格”时,输入已经为空

其实我不太懂英语,也许正确的句子是这样的:

  

当您按下“退格键”时,在按

之前输入已为空

好的,在输入中写一个字符,然后按退格键,会发生什么?该角色都将被删除,并将显示该警报。我需要在它们之间设置一个步骤,我的意思是我需要为这些事件分别设置两个退格。

一个用于删除最后一个字符的退格键,另一个用于显示该警报的退格键。我怎么能这样做?

2 个答案:

答案 0 :(得分:3)

您正在寻找的事件是mouseleave()

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" />来处理它:

class
  $("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');
        }
      }
  });

答案 1 :(得分:2)

改为使用keydown事件!

使用keyupinput的值已被清除,因此value==''将始终为真。

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