YouTip LogoYouTip

Example Autocomplete

Search and filter based on user input, allowing users to quickly find and select from a preset list of values. For more details about the Autocomplete widget, please see the API documentation (#). This chapter uses [search.php download](https://static.jyshare.com/download/search.php). ## Default Functionality When you type in the input field, the Autocomplete widget provides suggestions. In this example, suggestions for programming languages are provided. You can try typing "ja" to get Java or JavaScript. The data source is a simple JavaScript array, provided to the widget using the `source` option. jQuery UI Autocomplete - Default Functionality $(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" ]; $( "#tags" ).autocomplete({ source: availableTags }); });
## Accent Folding The autocomplete field uses a custom `source` option to match result items with accented characters, even if the text field does not contain accented characters. However, if you type an accented character in the text field, non-accented result items will not be displayed. Try typing "Jo" to see "John" and "JΓΆrn", then type "JΓΆ" to see only "JΓΆrn". jQuery UI Autocomplete - Accent Folding $(function() { var names = [ "JΓΆrn Zaefferer", "Scott GonzΓ‘lez", "John Resig" ]; var accentMap = { "Γ‘": "a", "ΓΆ": "o" }; var normalize = function( term ) { var ret = ""; for ( var i = 0; i < term.length; i++ ) { ret += accentMap[ term.charAt(i) ] || term.charAt(i); } return ret; }; $( "#developer" ).autocomplete({ source: function( request, response ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex( request.term ), "i" ); response( $.grep( names, function( value ) { value = value.label || value.value || value; return matcher.test( value ) || matcher.test( normalize( value ) ); }) ); } }); });
## Categories Categorized search results. Try typing "a" or "n". jQuery UI Autocomplete - Categories .ui-autocomplete-category { font-weight: bold; padding: .2em .4em; margin: .8em 0 .2em; line-height: 1.5; } $.widget( "custom.catcomplete", $.ui.autocomplete, { _renderMenu: function( ul, items ) { var that = this, currentCategory = ""; $.each( items, function( index, item ) { if ( item.category != currentCategory ) { ul.append( "
  • " + item.category + "
  • " ); currentCategory = item.category; } that._renderItemData( ul, item ); }); } }); $(function() { var data = [ { label: "anders", category: "" }, { label: "andreas", category: "" }, { label: "antal", category: "" }, { label: "annhhx10", category: "Products" }, { label: "annk K12", category: "Products" }, { label: "annttop C13", category: "Products" }, { label: "anders andersson", category: "People" }, { label: "andreas andersson", category: "People" }, { label: "andreas johnson", category: "People" } ]; $( "#search" ).catcomplete({ delay: 0, source: data }); }); ## Combobox A custom widget created with Autocomplete and Button. You can type some characters to get filtered results based on your input, or use the button to select from the full list. The input is read from an existing `select` element and passed to Autocomplete with a custom `source` option. This is an unsupported, imperfect widget. It is here purely to demonstrate autocomplete customization. [For more details on how this widget works, click here to view the related jQuery article.](http://www.learningjquery.com/2010/06/a-jquery-ui-combobox-under-the-hood/) jQuery UI Autocomplete - Combobox .custom-combobox { position: relative; display: inline-block; } .custom-combobox-toggle { position: absolute; top: 0; bottom: 0; margin-left: -1px; padding: 0; /* Support: IE7 */ *height: 1.7em; *top: 0.1em; } .custom-combobox-input { margin: 0; padding: 0.3em; } (function( $ ) { $.widget( "custom.combobox", { _create: function() { this.wrapper = $( "" ) .addClass( "custom-combobox" ) .insertAfter( this.element ); this.element.hide(); this._createAutocomplete(); this._createShowAllButton(); }, _createAutocomplete: function() { var selected = this.element.children( ":selected" ), value = selected.val() ? selected.text() : ""; this.input = $( "" ) .appendTo( this.wrapper ) .val( value ) .attr( "title", "" ) .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" ) .autocomplete({ delay: 0, minLength: 0, source: $.proxy( this, "_source" ) }) .tooltip({ tooltipClass: "ui-state-highlight" }); this._on( this.input, { autocompleteselect: function( event, ui ) { ui.item.option.selected = true; this._trigger( "select", event, { item: ui.item.option }); }, autocompletechange: "_removeIfInvalid" }); }, _createShowAllButton: function() { var input = this.input, wasOpen = false; $( "" ) .attr( "tabIndex", -1 ) .attr( "title", "Show All Items" ) .tooltip() .appendTo( this.wrapper ) .button({ icons: { primary: "ui-icon-triangle-1-s" }, text: false }) .removeClass( "ui-corner-all" ) .addClass( "custom-combobox-toggle ui-corner-right" ) .mousedown(function() { wasOpen = input.autocomplete( "widget" ).is( ":visible" ); }) .click(function() { input.focus(); // If already visible, close if ( wasOpen ) { return; } // Pass empty string as search value to display all results input.autocomplete( "search", "" ); }); }, _source: function( request, response ) { var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" ); response( this.element.children( "option" ).map(function() { var text = $( this ).text(); if ( this.value && ( !request.term || matcher.test(text) ) ) return { label: text, value: text, option: this }; }) ); }, _removeIfInvalid: function( event, ui ) { // Selected an item, do nothing if ( ui.item ) { return; } // Search for a match (case insensitive) var value = this.input.val(), valueLowerCase = value.toLowerCase(), valid = false; this.element.children( "option" ).each(function() { if ( $( this ).text().toLowerCase() === valueLowerCase ) { this.selected = valid = true; return false; } }); // Found a match, do nothing if ( valid ) { return; } // Remove invalid value this.input .val( "" ) .attr( "title", value + " didn't match any item" ) .tooltip( "open" ); this.element.val( "" ); this._delay(function() { this.input.tooltip( "close" ).attr( "title", "" ); }, 2500 ); this.input.data( "ui-autocomplete" ).term = ""; }, _destroy: function() { this.wrapper.remove(); this.element.show(); } }); })( jQuery ); $(function() { $( "#combobox" ).combobox(); $( "#toggle" ).click(function() { $( "#combobox" ).toggle(); }); });
    Choose... ActionScript AppleScript Asp BASIC C C++ Clojure COBOL ColdFusion Erlang Fortran Groovy Haskell Java JavaScript Lisp Perl PHP Python Ruby Scala Scheme
    ## Custom Data and Display You can use custom data formats and display data by simply overriding the default focus and select behaviors. Try typing "j" or pressing the down arrow key to get a list of items. jQuery UI Autocomplete - Custom Data and Display #project-label { display: block; font-weight: bold; margin-bottom: 1em; } #project-icon { float: left; height: 32px; width: 32px; } #project-description { margin: 0; padding: 0; } $(function() { var projects = [ { value: "jquery", label: "jQuery", desc: "the write less, do more, JavaScript library", icon: "jquery_32x32.png" }, { value: "jquery-ui", label: "jQuery UI", desc: "the official user interface library for jQuery", icon: "jqueryui_32x32.png" }, { value: "sizzlejs", label: "Sizzle JS", desc: "a pure-JavaScript CSS selector engine", icon: "sizzlejs_32x32.png" } ]; $( "#project" ).autocomplete({ minLength: 0, source: projects, focus: function( event, ui ) { $( "#project" ).val( ui.item.label ); return false; }, select: function( event, ui ) { $( "#project" ).val( ui.item.label ); $( "#project-id" ).val( ui.item.value ); $( "#project-description" ).html( ui.item.desc ); $( "#project-icon" ).attr( "src", "images/" + ui.item.icon ); return false; } }) .data( "ui-autocomplete" )._renderItem = function( ul, item ) { return $( "
  • " ) .append( "" + item.label + "
    " + item.desc + "
    " ) .appendTo( ul ); }; });
    Select a project (type "j"):

    ## Multiple Values Usage: Type some characters, like "j", to see related programming language results. Select a value, then continue typing characters to add other values. This example demonstrates how to use the `source` option and some events to implement multiple autocomplete values in a single text field. jQuery UI Autocomplete - Multiple Values $(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" ]; function split( val ) { return val.split( /,s*/ ); } function extractLast( term ) { return split( term ).pop(); } $( "#tags" ) // Don't navigate away from the field on tab when selecting an item .bind( "keydown", function( event ) { if ( event.keyCode === $.ui.keyCode.TAB && $( this ).data( "ui-autocomplete" ).menu.active ) { event.preventDefault(); } }) .autocomplete({ minLength: 0, source: function( request, response ) { // Delegate back to original list, but only those that match the current term response( $.ui.autocomplete.filter( availableTags, extractLast( request.term ) ) ); }, focus: function() { // Prevent value inserted on focus return false; }, select: function( event, ui ) { var terms = split( this.value ); // Remove the current input terms.pop(); // Add the selected item terms.push( ui.item.value ); // Add placeholder to get the comma-and-space at the end terms.push( "" ); this.value = terms.join( ", " ); return false; } }); });
  • ← Example ButtonExample Accordion β†’