简体   繁体   中英

jQuery Autocomplete a input field for a filter table

In my program, I have a table which I filter with an input field. You type something in the search/input field and the table gets filtered immediately without pressing enter.

Now I wanted to add autocomplete to this input field and it works but there is one problem. When I start typing something into the input field, I get suggestions. Now I can click on a suggestion and it gets written in the input field. That works just fine. But my table doesn't get filtered until I press enter and that's my problem. How do I make it that it automatically submits it/filters the table without pressing enter after selecting a suggestion?

Here are my two functions for the filtering and the autocomplete.

$("#searchInput").autocomplete({
    source: availableTags, //array with all possible search results of the table
});

$(document).ready(function(){
    $("#searchInput").on("keyup", function () {
        var value = $(this).val().toLowerCase();
        $("#contractTable tr").filter(function(){
             $(this).toggle($(this).find(".target").text().toLowerCase().indexOf(value) > -1) // I only want to search for two specific  cells of every row thats why I use find(".target")
        });
    });
});

I hope you get what I'm trying to achieve and on a side note I'm pretty new to JavaScript and jQuery so please have mercy with me :)

Here I fixed that for you: https://jsfiddle.net/eakumopw/1/

Your Problem is you only hooked the filtering event to "keyup" . But selecting a autocomplete suggestions is no key-up event. Adding another event won't solve the problem either because the suggestions-box is a different element.

I check which events jquery-autocomplete supports ( http://tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Events.php ) and found the close() event to be the solution for me.

I outsourced the filtering process into a new function doFilter( value ) and made a call to that function on the close event of jquery-autcomplete.

$("#myInput").autocomplete({
  source: availableTags,
  close: function(event, ui) {
    console.log("close");
    doFilter($("#myInput").val().toLowerCase());
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM