Home > database >  How can I check if input is <=2 or undefined with jQuery?
How can I check if input is <=2 or undefined with jQuery?

Time:11-29

The length <= 2 check is working ONLY if I'm manually erasing the text from the input. However, My input has closing button which has reset(); on it, and when I'm pressing it, my input is empty, however jquery code doesnt care about that and doesnt recognise the input as empty, because as I know the reset(); function turns my input form to undefined.. so I have to check the input for undefined in my jQuery, however it doesn't work. any clues??

<script>
    $('.regulator').keyup(function() {
      
      if ($(this).val().length <= 2 || $(this).val().value == undefined) {
        $('.quickSearchResults').hide();
      }  else {
        $('.quickSearchResults').show();
      }
    }).keyup();
    </script>

CodePudding user response:

I suggest you use this instead:

  1. use .on("input" since it handles paste too
  2. reuse the toggle function on click, on input and on load
  3. add a timeout on the reset

$(function() {
  const $reg = $('.regulator');
  const $qs = $('.quickSearchResults');
  const $rst = $("#rst");
  const toggleQS = () => {
    const val = $reg.val();
    $qs.toggle(val.length > 2);
  };
  $reg.on("input", toggleQS);
  $rst.on("click", () => setTimeout(toggleQS,10));
  toggleQS(); // in case there is data already
})
.quickSearchResults {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="myForm">
  <input  id="someId" name="someName" value="More than 2" />
  <input type="reset" id="rst" />
</form>
<div >Results</div>

CodePudding user response:

There is really no reason to check for undefined if you are using the value of the input the user is typing in. .val() is not going to return undefined when the user is interacting with it.

$('.regulator').keyup(function() {
  
  if ($(this).val().length <= 2) {
    $('.quickSearchResults').hide();
  }  else {
    $('.quickSearchResults').show();
  }
}

Now if you really want to check for undefined, do that check first

$('.regulator').keyup(function() {
  var val = $(this).val()
  if (val === undefined || val.length <= 2) {
    $('.quickSearchResults').hide();
  }  else {
    $('.quickSearchResults').show();
  }
}

how most people would code this

$('.regulator').on('input', function() {
    $('.quickSearchResults').toggle(val.length > 2);
}).trigger('input');

Now to handle reset, listen to the event.

$('#yourForm').on("reset", function () {
  $('.quickSearchResults').hide();
});

or

$('#yourForm').on("reset", function () {
  window.setTimeout(function () {
    $('.regulator').trigger('input');
  });
});
  • Related