Search code examples
jquerylivesearch

jQuery live search when 4 numbers entered


How do I do a live search only once the user has typed in 4 numbers into the input?

It basically needs to contact the php page using $ajax which I already have.

I thought it might be an input.length == 4 but I tried it and failed.


Solution

  • You can use regular expressions to check if the value of the input consists exactly of four digits.

    $("#test").keyup(function() {
      if(/^\d{4}$/.test($(this).val())) {
        alert('please call $.ajax here');
      }
    });
    

    where #test is:

    <input type="text" id="test" />
    

    HERE is the code.