jquery ui autocomplete: count results

久未见 提交于 2019-12-22 08:37:35

问题


i would like to know if theres a way to count the number of results which are displayed when you type something in the textbox. Count the li-elements work, but i bet theres a smarter way. Thanks


回答1:


I think that this is not possible directly using JQueryUI Events. I've looking for a way without success.

All the events associated only return the element clicked (after the list is displayed), or information about the event (not about the list).

You can see it here: http://jqueryui.com/demos/autocomplete/#event-focus

What you said is the most closely solution:

$( "#tags" ).autocomplete({
  source: availableTags,
  open: function(event,ui){
    var len = $('.ui-autocomplete > li').length;
    $('#count').html('Founded '+len+' results');
  }
});



回答2:


The solution above did not work for me when I was typing something that returns no results. It keeps showing the amount of results from the last matching string. Here's a solution that did work.

source: function (request, response) {
    $.getJSON(
        "/Ajax/GetSomeJson.ashx",
        { q: request.term },
        function (data) {
            console.log(data.length);
             $('#count').html('Found '+ data.length +' results');

            response($.map(data, function (item) {
                return item;
            }));
        }
    );
}



回答3:


I found a way to count the matches found, based on Fran's answer, but I think it's not 100% reliable. Still, it works for me.

$('#autocompleteinput').autocomplete({
    source: datasource,
    search: function()
    {
        $(this).data('count',0);
    },
    open: function()
    {
        $(this).data('count',$('.ui-autocomplete > li').length);
    },
    delay: 0
}).keyup(function(){
    $('#count').html('Found '+$(this).data('count')+' items');
});

The delay has to be 0, or often it will trigger the keyup before the search and it won't count well.




回答4:


This is Working for me. My requirement is to auto select on on blur event if there is only one matching result. Previously I tried var len= $('.ui-autocomplete > li').length; but i did not work in all scenarios. Sometimes it adds up previous results to count/length.

Below code worked for me:

.on('autocompletechange', function() {
        if ($(this).data('ui-autocomplete').selectedItem === null && ($(this).autocomplete("widget").find( "li" ).length == 1) ) {
            //this will trigger your select automatically so it will handle other custom override you did for select
            $(this).data('ui-autocomplete').menu.element.children('li:first').children('a').trigger('click');
        }
    })


来源:https://stackoverflow.com/questions/5538358/jquery-ui-autocomplete-count-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!