简体   繁体   English

jQuery 自动完成过滤表的输入字段

[英]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.您在搜索/输入字段中输入内容,表格会立即被过滤,无需按 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 :)我希望你能得到我想要实现的目标,顺便说一句,我对 JavaScript 和 jQuery 还很陌生,所以请怜悯我 :)

Here I fixed that for you: https://jsfiddle.net/eakumopw/1/在这里,我为您解决了这个问题: https : //jsfiddle.net/eakumopw/1/

Your Problem is you only hooked the filtering event to "keyup" .您的问题是您只将过滤事件挂钩到"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.我检查了 jquery-autocomplete 支持哪些事件( http://tutorialspark.com/jqueryUI/jQuery_UI_AutoComplete_Events.php )并发现close()事件是我的解决方案。

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.我将过滤过程外包给一个新函数doFilter( value )并在 jquery-autcomplete 的close事件上调用该函数。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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