简体   繁体   中英

jQuery Autocomplete search bar

I am trying to design an autocomplete search bar and everything is working fine except that I want to insert a new function which displays "No search results" if the user can't find any results. I want this to be displayed in the widget itself. I mean in the autocomplete window.

Should I be using any event? I have no idea. Any help is much appreciated!

Thank you.

Here's is my javascript

var SearchBar = (function($) {
var search_data = function( request, response ) {
 $.ajax({
    url: "/search.json",
    dataType: "json",
    type: "GET",            
    data: {q: request.term },
    success: function( data ) {
        response( $.map( data, function( item ) {
            return {
                label: item.label,
                id: item.id
              };
           }));
       }
   });
};

$("#searchfield").autocomplete({
    source: search_data,
    minLength: 1
 }); 

 };

}) (jQuery); 

I think you could get help from this example :

$(function() {
var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
    ];

var NoResultsLabel = "No Results";

$("#tags").autocomplete({
    source: function(request, response) {
        var results = $.ui.autocomplete.filter(availableTags, request.term);

        if (!results.length) {
            results = [NoResultsLabel];
        }

        response(results);
    },
    select: function (event, ui) {
        if (ui.item.label === NoResultsLabel) {
            event.preventDefault();
        }
    },
    focus: function (event, ui) {
        if (ui.item.label === NoResultsLabel) {
            event.preventDefault();
        }
    }
});
});

Also you can Visit this link and i hope this helps you !

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