jquery keyup show/hide stay shown when backspaced

问题: So I got this fiddle: https://jsfiddle.net/htz8x1no/ which basically runs on this code: $('.relevant-results').hide(); $('#input').keyup(function() {...

问题:

So I got this fiddle: https://jsfiddle.net/htz8x1no/ which basically runs on this code:

      $('.relevant-results').hide();

      $('#input').keyup(function() {
        if ($(this).val().length < 3) {
          $('.relevant-results').hide();
        } else {
          $('.relevant-results').show();
        }
      });

When you put more then 3 characters in the input it will show the div otherwise it will hide it. This works as expected but I would like to keep the div visible when the user removes(backspaces) a part of it.

So this keyup function should only run the first time the user inputs. Is it possible to do this with jQuery/JS?


回答1:

You could just test to see if the input is greater than or equal to three and then show the div. No need for the logic to hide it.

$('.relevant-results').hide();
      
$('#input').keyup(function() {
   if ($(this).val().length >= 3) {
      $('.relevant-results').show();
   }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div class="relevant-results">
  Hello
</div>


回答2:

Use backspace key code like this.

$('.relevant-results').hide();

$('#input').keyup(function (e) {
  if ($(this).val().length < 3) {
    if (e.keyCode == 8) {
    } else {
      $('.relevant-results').hide();
    }
  } else {
    $('.relevant-results').show();
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="input">
<div class="relevant-results">
  Hello
</div>

  • 发表于 2019-12-25 17:29
  • 阅读 ( 252 )
  • 分类:网络文章

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除