Search code examples
jquerylivesearch

Jquery live search, doesnt exit if statement once content is removed from the input


I am currently in a final team project for my training as a web developer. And i did wrote a live search code for our application and it works as intended until the point i remove the content from the input. The code stays sometimes in the if statement to remove the append. And i dont see why. Does someone know?

Here is my code:

$(function(){

 var check = 0;

 $("#getQuestions").on("keyup", function(){
    check++;

    var inputLength = $("#getQuestions").val().length;

    if (check === 3 || inputLength === 0) {

        $(".liveSearch").remove();

    }
    if (inputLength >= 1) {

        if(check === 3 ){

            $.ajax({

                type: "POST",
                url: "/getQuestions",
                data: {"question": $("#getQuestions").val()}

            }).done(function(response){

                for (var i = 0; i < response.length; i++) {

                    var id = response[i].id;
                    var title = response[i].title;
                    $("#listQuestions").append('<div class="liveSearch"><a href="/question?id='+id +'""' + '>' + title + '</a></div>' );

                }

                check = 0;

            });

        }
    }


 });


});

I appreciate the help.

Have a nice day.


Solution

  • You seem to be overcomplicating things by using a count var. Right now your ajax call only triggers for every 3 key ups (which means issues with for instance pressing shift 3 times will trigger it or pressing and holding a letter will only increase count by 1).

    By using keypress and a timer instead, you'll get the following code:

    $(function(){
      var timer;
      $("#getQuestions").on("keypress", function(){
        if ($("#getQuestions").val().length == 0) {
          $(".liveSearch").remove();
        }
        if ($("#getQuestions").val().length > 0) {
          clearTimeout(timer);
          timer = setTimeout(function() {
            $(".liveSearch").remove();
            $.ajax({
              type: "POST",
              url: "/getQuestions",
              data: {"question": $("#getQuestions").val()}
            }).done(function(response){
              for (var i = 0; i < response.length; i++) {
                $("#listQuestions").append('<div class="liveSearch"><a href="/question?id=' + response[i].id + '">' + response[i].title + '</a></div>');
              }
            });
          }, 1000);
        }
      });
    });