Search code examples
javascriptjqueryhideshowkeyup

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() {
        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?


Solution

  • 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>