joy08
joy08

Reputation: 9662

How to clear the previous search results once you clear the textbox

I am trying to implement Autocomplete using JSP and AJAX and jquery. The search results inside div tag are not clearing even after I clear contents within the text-box

HTML snippet:

<div class="form-group">
  <label for="message-text">Employee Name:</label>
  <input ng-model="names" align="left" type="text" name="name" id="name" class="form-control" autocomplete="off" placeholder="Enter a Name" required />
  <div id="myDIV">
    <div id="nameList" class="namecontent"></div>
  </div>
</div>

Jquery code:

$(document).ready(function() {

    $('#name1').keyup(function() {
        var query = $(this).val();
        if(query != '') {

            $.ajax({
                url: "names.jsp",
                method: "POST",
                data: { query: query },
                success: function(data) {
                    $('#nameList1').fadeIn();
                    $('#nameList1').html(data);
                }
            });
        }
    });

    $(document).on('click','li',function() {
        //alert($(this).text());
        $('#name1').val($(this).text());
        $('#nameList1').fadeOut();
    });

});

I want to clear all the search results ,after i clear the textbox. Can someone help me how to do this?

Upvotes: 1

Views: 1181

Answers (1)

Koby Douek
Koby Douek

Reputation: 16693

You're already checking if (query != ''), so you can just add an else which clears the nameList1 from its content:

if(query != '')
{
    $.ajax({
        url:"names.jsp",
        method:"POST",
        data:{query:query},
        success:function(data) {
            $('#nameList1').fadeIn();
            $('#nameList1').html(data);
        }
   });
}
else {
    // clear the results
    $('#nameList1').html('');
}

Upvotes: 2

Related Questions