Giter VIP home page Giter VIP logo

jquery-autocomplete's Introduction

Ajax Autocomplete for jQuery

Ajax Autocomplete for jQuery allows you to easily create autocomplete/autosuggest boxes for text input fields.

It has no dependencies other than jQuery.

The standard jquery.autocomplete.js file is around 13KB when minified.

API

The following sets up autocomplete for input fields where options is an object literal that defines the settings to use for the autocomplete plugin. All available option settings are shown in the tables below.

$(selector).autocomplete(options);

General settings (local and Ajax)

Setting Default Description
noCache false Boolean value indicating whether to cache suggestion results
delimiter optional String or RegExp, that splits input value and takes last part to as query for suggestions. Useful when for example you need to fill list of comma separated values.
minChars 1 Minimum number of characters required to trigger autosuggest
triggerSelectOnValidInput true Boolean value indicating if select should be triggered if it matches suggestion
preventBadQueries true Boolean value indicating if it should prevent future Ajax requests for queries with the same root if no results were returned. E.g. if Jam returns no suggestions, it will not fire for any future query that starts with Jam
autoSelectFirst false If set to true, first item will be selected when showing suggestions
beforeRender optional function (container, suggestions) {} called before displaying the suggestions. You may manipulate suggestions DOM before it is displayed
formatResult optional function (suggestion, currentValue) {} custom function to format suggestion entry inside suggestions container
formatGroup optional function (suggestion, category) {} custom function to format group header
groupBy optional property name of the suggestion data object, by which results should be grouped
maxHeight 300 Maximum height of the suggestions container in pixels
width auto Suggestions container width in pixels, e.g.: 300, flex for max suggestion size and auto takes input field width
zIndex 9999 'z-index' for suggestions container
appendTo optional Container where suggestions will be appended. Default value document.body. Can be jQuery object, selector or HTML element. Make sure to set position: absolute or position: relative for that element
forceFixPosition false Suggestions are automatically positioned when their container is appended to body (look at appendTo option), in other cases suggestions are rendered but no positioning is applied. Set this option to force auto positioning in other cases
orientation bottom Vertical orientation of the displayed suggestions, available values are auto, top, bottom. If set to auto, the suggestions will be orientated it the way that place them closer to middle of the view port
preserveInput false If true, input value stays the same when navigating over suggestions
showNoSuggestionNotice false When no matching results, display a notification label
noSuggestionNotice No results Text or htmlString or Element or jQuery object for no matching results label
onInvalidateSelection optional function () {} called when input is altered after selection has been made. this is bound to input element
tabDisabled false Set to true to leave the cursor in the input field after the user tabs to select a suggestion

Event function settings (local and Ajax)

Event setting Function description
onSearchStart function (params) {} called before Ajax request. this is bound to input element
onHint function (hint) {} used to change input value to first suggestion automatically. this is bound to input element
onSearchComplete function (query, suggestions) {} called after Ajax response is processed. this is bound to input element. suggestions is an array containing the results
transformResult function(response, originalQuery) {} called after the result of the query is ready. Converts the result into response.suggestions format
onSelect function (suggestion) {} Callback function invoked when user selects suggestion from the list. this inside callback refers to input HtmlElement.
onSearchError function (query, jqXHR, textStatus, errorThrown) {} called if Ajax request fails. this is bound to input element
onHide function (container) {} called before container will be hidden

Local only settings

Setting Default Description
lookupLimit no limit Number of maximum results to display for local lookup
lookup n/a Callback function or lookup array for the suggestions. It may be array of strings or suggestion object literals
suggestion n/a Not a settings, but in the context of above row, a suggestion is an object literal with the following format: { value: 'string', data: any }
lookupFilter n/a function (suggestion, query, queryLowerCase) {} filter function for local lookups. By default it does partial string match (case insensitive)

Ajax only settings

Setting Default Description
serviceUrl n/a Server side URL or callback function that returns serviceUrl string
type GET Ajax request type to get suggestions
dataType text type of data returned from server. Either text, json or jsonp, which will cause the autocomplete to use jsonp. You may return a json object in your callback when using jsonp
paramName query The name of the request parameter that contains the query
params optional Additional parameters to pass with the request
deferRequestBy 0 Number of miliseconds to defer Ajax request
ajaxSettings optional Any additional Ajax Settings that configure the jQuery Ajax request

Default Options

Default options for all instances can be accessed via $.Autocomplete.defaults.

Instance Methods

Autocomplete instance has following methods:

  • setOptions(options): you may update any option at any time. Options are listed above.
  • clear: clears suggestion cache and current suggestions.
  • clearCache: clears suggestion cache.
  • disable: deactivate autocomplete.
  • enable: activates autocomplete if it was deactivated before.
  • hide: hides suggestions.
  • dispose: destroys autocomplete instance. All events are detached and suggestion containers removed.

There are two ways that you can invoke Autocomplete method. One is calling autocomplete on jQuery object and passing method name as string literal. If method has arguments, arguments are passed as consecutive parameters:

$('#autocomplete').autocomplete('disable');
$('#autocomplete').autocomplete('setOptions', options);

Or you can get Autocomplete instance by calling autcomplete on jQuery object without any parameters and then invoke desired method.

$('#autocomplete').autocomplete().disable();
$('#autocomplete').autocomplete().setOptions(options);

Usage

Html:

<input type="text" name="country" id="autocomplete"/>

Ajax lookup:

$('#autocomplete').autocomplete({
    serviceUrl: '/autocomplete/countries',
    onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

Local lookup (no Ajax):

var countries = [
    { value: 'Andorra', data: 'AD' },
    // ...
    { value: 'Zimbabwe', data: 'ZZ' }
];

$('#autocomplete').autocomplete({
    lookup: countries,
    onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

Custom lookup function:

$('#autocomplete').autocomplete({
    lookup: function (query, done) {
        // Do Ajax call or lookup locally, when done,
        // call the callback and pass your results:
        var result = {
            suggestions: [
                { "value": "United Arab Emirates", "data": "AE" },
                { "value": "United Kingdom",       "data": "UK" },
                { "value": "United States",        "data": "US" }
            ]
        };

        done(result);
    },
    onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

Styling

Generated HTML markup for suggestions is displayed below. You may style it any way you'd like.

<div class="autocomplete-suggestions">
    <div class="autocomplete-group"><strong>NHL</strong></div>
    <div class="autocomplete-suggestion autocomplete-selected">...</div>
    <div class="autocomplete-suggestion">...</div>
    <div class="autocomplete-suggestion">...</div>
</div>

Style sample:

.autocomplete-suggestions { border: 1px solid #999; background: #FFF; overflow: auto; }
.autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; }
.autocomplete-selected { background: #F0F0F0; }
.autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
.autocomplete-group { padding: 2px 5px; }
.autocomplete-group strong { display: block; border-bottom: 1px solid #000; }

Response Format

Response from the server must be JSON formatted following JavaScript object:

{
    // Query is not required as of version 1.2.5
    "query": "Unit",
    "suggestions": [
        { "value": "United Arab Emirates", "data": "AE" },
        { "value": "United Kingdom",       "data": "UK" },
        { "value": "United States",        "data": "US" }
    ]
}

Data can be any value or object. Data object is passed to formatResults function and onSelect callback. Alternatively, if there is no data you can supply just a string array for suggestions:

{
    "query": "Unit",
    "suggestions": ["United Arab Emirates", "United Kingdom", "United States"]
}

Non standard query/results

If your Ajax service expects the query in a different format, and returns data in a different format than the standard response, you can supply the "paramName" and "transformResult" options:

$('#autocomplete').autocomplete({
    paramName: 'searchString',
    transformResult: function(response) {
        return {
            suggestions: $.map(response.myData, function(dataItem) {
                return { value: dataItem.valueField, data: dataItem.dataField };
            })
        };
    }
})

Grouping Results

Specify groupBy option of you data property if you wish results to be displayed in groups. For example, set groupBy: 'category' if your suggestion data format is:

[
    { value: 'Chicago Blackhawks', data: { category: 'NHL' } },
    { value: 'Chicago Bulls', data: { category: 'NBA' } }
]

Results will be formatted into two groups NHL and NBA.

Known Issues

If you use it with jQuery UI library it also has plugin named autocomplete. In this case you can use plugin alias devbridgeAutocomplete:

$('.autocomplete').devbridgeAutocomplete({ ... });

It seems that for mobile Safari click events are only triggered if the CSS of the object being tapped has the cursor set to pointer:

.autocomplete-suggestion { 
    cursor: pointer;
}

See issue #542

License

Ajax Autocomplete for jQuery is freely distributable under the terms of an MIT-style license.

Copyright notice and permission notice shall be included in all copies or substantial portions of the Software.

Authors

Tomas Kirda / @tkirda

jquery-autocomplete's People

Contributors

arash-khajelou avatar armno avatar balvig avatar ericsaboia avatar erikschierboom avatar erotte avatar fpupor avatar gedbac avatar geoffrosen avatar glowka avatar gouigouix avatar janfoeh avatar jesseditson avatar jisaac01 avatar jrochkind avatar loganarnett avatar macool avatar martinduparc avatar mmcev106 avatar mrsam avatar nilsga avatar oshihirii avatar qqilihq avatar rickycezar avatar rushimusmaximus avatar silvenon avatar stonio avatar sunbox avatar swey avatar tkirda avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery-autocomplete's Issues

The suggestion container should be remove before creating new one.

Hi Tomas Kirda,

First of all, I want to say my thanks to you for your best work. I am using your auto-complete library. It works fine besides a small problem that I want to share to you now.

The issue happens when I try to initialize auto complete for a text field many times. It is because that the container is created without checking if the same container has already initialized. It comes in the function initialize function:

// Determine suggestions width:
if (!options.width || options.width === 'auto') {
options.width = that.el.outerWidth();
}

        that.suggestionsContainer = Autocomplete.utils.createNode('<div class="' + options.containerClass + '" style="position: absolute; display: none;"></div>');

        container = $(that.suggestionsContainer);

        container.appendTo(options.appendTo).width(options.width);

This leads to the problem it displays many suggestion containers.

A work-around to fix it works on my project, I check and remove the old container from the body, like this:

        var containerId = that.element.id + "SuggestionContainer";
        // Remove existing containers.
        $('#' + containerId).remove();

        that.suggestionsContainer = Autocomplete.utils.createNode('<div id="' + containerId + '" class="' + options.containerClass + '" style="position: absolute; display: none;"></div>');

I would like to announce you this issue, and I hope you can fix it with a better solution.

Thanks and cheers,
Binh

disable() or enable() doesn't work

...
var ac = $('#query').autocomplete(options);
...
ac.disable();
ac.enable();

  • doesn't work! i got errors like "Uncaught TypeError: Object [object Object] has no method 'disable'" in Chrome or "TypeError: ac.disable is not a function" in Firefox

ignoreValueChange

What is the purpose of this flag? It seems to cause problems for me when erasing characters in the autocomplete field after selecting a value. I would expect the autocomplete to run a new query, but that does not happen.

serviceUrl not working?

Hi guys,

I used Autocomplete version 1.1.5 - on another project - it worked great. I made a lot of changes to that code -- so thought it would come here to download a new fresh version.

BUT...

I cannot get serviceUrl to work any more?

index.htm...

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="src/jquery_autocomplete.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
    var a1;
    a1 = $('#myText').autocomplete({
        serviceUrl: 'data/',
        width: 448,
        delimiter: /(,|;)\s*/,
        onSelect: function (suggestion) {
                alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
        }
    });      
 })
</script>
</head>
<body>
<input type="text" id="myText" value="" maxlength="11" />
</body>
</html>

data/index.php

{query: "Unit",suggestions: ["United Arab Emirates", "United Kingdom", "United States"]}

The json request comes back -- but firefox shows this error:

SyntaxError: JSON.parse: expected property name or '}' - jquery line 1

Can anyone help - is there a fault with the code?

Cheers.

Patch: Drop down suggestions

I use your library for my web site and I needed a way to display the whole suggestions because I pre fill the auto completion.

The patch don't alter the rest of the library.

to use this function use $("myelement").autocomplete('display');

Best regards and thanks for you work

The patch (don't want to fork the project):

diff --git a/src/jquery.autocomplete.js b/src/jquery.autocomplete.js
index 245b3b1..220bea7 100644
--- a/src/jquery.autocomplete.js
+++ b/src/jquery.autocomplete.js
@@ -610,6 +610,33 @@
             }

             return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
+        },
+        
+        display: function() {
+            var that = this,
+                className = that.classes.suggestion,
+                suggestionSelector = '.' + that.classes.suggestion,
+                container = $(that.suggestionsContainer),
+                html = '';
+                
+            $.each(that.options.lookup, function(i, suggestion) {
+                that.suggestions.push(suggestion.value);
+                html += '<div class="' + className + '" data-index="' + i + '">' + suggestion.value + '</div>';
+            });
+            
+            container.html(html).show();
+            that.visible = true;
+
+            // reinstall handler
+            container.on('click', suggestionSelector, function () {
+                that.el.val(that.suggestions[$(this).data('index')]);
+            });
+
+            // Select first value by default:
+            if (that.options.autoSelectFirst) {
+                that.selectedIndex = 0;
+                container.children().first().addClass(classSelected);
+            }
         }
     };

Patch: Drop down suggestions (part 2)

I use your library for my web site and I needed a way to display the whole suggestions because I pre fill the auto completion.

The patch don't alter the rest of the library.

to use this function use $("myelement").autocomplete('display');

Best regards and thanks for you work (the bug is corrected)

The patch (don't want to fork the project):

diff --git a/src/jquery.autocomplete.js b/src/jquery.autocomplete.js
index 245b3b1..ae9271d 100644
--- a/src/jquery.autocomplete.js
+++ b/src/jquery.autocomplete.js
@@ -610,6 +610,35 @@
             }

             return currentValue.substr(0, currentValue.length - parts[parts.length - 1].length) + value;
+        },
+
+        display: function() {
+            var that = this,
+                className = that.classes.suggestion,
+                suggestionSelector = '.' + that.classes.suggestion,
+                container = $(that.suggestionsContainer),
+                html = '';
+                
+            that.suggestions = [];
+            
+            $.each(that.options.lookup, function(i, suggestion) {
+                that.suggestions.push(suggestion.value);
+                html += '<div class="' + className + '" data-index="' + i + '">' + suggestion.value + '</div>';
+            });
+            
+            container.html(html).show();
+            that.visible = true;
+
+            // reinstall handler
+            container.on('click', suggestionSelector, function () {
+                that.el.val(that.suggestions[$(this).data('index')]);
+            });
+
+            // Select first value by default:
+            if (that.options.autoSelectFirst) {
+                that.selectedIndex = 0;
+                container.children().first().addClass(classSelected);
+            }
         }
     };

query index name match client and server side.

Maybe you could put on documentation that the paramName must match in the server response and if I omit the paramName the data will not be displayed.

Or make it more flexible/defensive.

The demo isn't too much helpful.

Hi,

The demo isn't as much helpful as someone may expect. I think the docs on the page are better. Can I update the readme to include the page docs?

I also find that I can use functions to the params option and this way, I can make a autocomplete based on two fields:

$('#city').autocomplete({
    minChars: 2,
    deferRequestBy: 50,
    params: {state: function() { return $('#state').val()}},
    serviceUrl: city_w.data('autocomplete-url'),
}); 

I can add a note to this in the readme too.

Evolution request : Keyboard behavior don't launch onSelect callback

Many thanks for your product small and very useful (everything i like in a component). I spent many times trying to find a small jquery plugin which could help me to build a live search tool (not exactly an autocomplete tool), and finally your product was the only one i kept for my project. Other tools were bad for many reasons (too big, too much functions and nothing useful for my usecase).

So with your tool, it's possible to build a live search (using the onSelect and formatResult options).

But as I said in the title, we don't get the same behavior on mouse selection or in keyboard selection. The onSelect callback is not used with keyboard.

I've just changed the line 583 in jquery.autocomplete.js (in adjustScroll function)

old code : that.el.val(that.getValue(that.suggestions[index].value));

new code : that.onSelect(index);

For me it works, but perhaps we could need a more specific callback on keyboard events ( new option onKeyBoardSelect).

Best regards

JSONP support

I'd like to have JSONP support on this plugin - jQuery already does the heavy lifting here, only a few changes are needed to support it.

Hidden associative array

Hi,

I patched the code so i can have an hidden associative array of my values passed to lookup option :

onSelect: function (i) {
var me, fn, s, d, hv;
me = this;
fn = me.options.onSelect;
s = me.suggestions[i];
hv = me.options.hidden[me.options.lookup.suggestions.indexOf(s)];
d = me.data[i];
me.el.val(me.getValue(s));
if ($.isFunction(fn)) { fn(s, d, me.el, hv); }
},

It's simple to use: For example, i want to list users and keep their id hidden in database, i would use :

lookup : 'One,Two,Three'.split(','), hidden: '1,2,3'.split(',')

Keep in mind that it's not a real associative array since there is two independant array but i you use it correctly, it does the right job. I think it would be better to use a real associative array :)

Arrow Up And Down Navigation

Hi,

First of all thanks for making our life easier by creating such a cool stuff.

Finally, we've set up everything except up and down arrow keys functionality.

In your website if we search something we can navigate the result with keyboard:- up and down arrow keys but in our code it's not working, we tried my best but I couldn't figure out, we're in midst of revamp our whole website structure http://learnenglish24x7.com/ If you wish we can provide you the password protected admin page where we are testing and running the code.

FYI: We also checked Bison Office website and their code is working perfectly fine so we analyzed their source code and found they are using 1.1 version whereas we are using latest version 1.1.5 even then it's not working.

Could you please shed some light on this issue, I'm having to select only through mouse which doesn't get ease of comfort?

Suggestions overflow browser width when window width reduced

When the browser width is reduced, the left position of div.autocomplete-suggestions may lie outside the viewport even though the input field does not. This causes an unnecessary horizontal scrollbar to be displayed. To reproduce this problem, please follow these steps:

  • open the demo app on a fairly large monitor such that the initial left position of .autocomplete-suggestions is something like 560px
  • make the browser narrower, by dragging the right-hand edge leftwards. At some point the position of .autocomplete-suggestions will lie outside the visible portion of the screen even though the input field(s) do not.
  • at this point a horizontal scrollbar will appear (in order to accommodate the invisible .autocomplete-suggestions element). However, to the user this scrollbar seems useless because there is no (visible) content in the scrollable area.

This problem only occurs on Firefox. I guess if you update the left position of .autocomplete-suggestions when the browser width is changed (just as you do when the input field is activated), it would resolve this problem.

update misleading docs

The docs here:

http://www.devbridge.com/projects/autocomplete/jquery/

that describe the expected JSON response and the onSelect function are not consistent with the latest version. The expected JSON response is described as:

{
  query:'Li',
  suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania'],
  data:['LR','LY','LI','LT']
}

But it should be:

{
  query:'Li',
  suggestions:[
    {"value":"Liberia","data": "LR"},
    {"value":"Libyan Arab Jamahiriya',"data": "LY"},
    {"value":"Liechtenstein","data": "LI"},
    {"value":"Lithuania","data": "LT"}
  ]
}

And the example callback function should be changed from:

onSelect: function(value, data){ alert('You selected: ' + value + ', ' + data); }

to:

onSelect: function(suggestion){ alert('You selected: ' + suggestion.value + ', ' + suggestion.data); }

It would be helpful if in future breaking changes like this were mentioned prominently in the docs.

Disable selection list if no results found

Hi!

Is there a way to disable the selection list if the search query did not return any values? Or, if we get the string "No matches" back to make that element not "selectable"?

What I want to do is that if a search does not find any matches then I'd like to keep whatever is already entered in in the input field. Is that possible?

Thanks!!

Deselect item when mouse moves out of the suggestions.

Country name: when I type in for example "P" letter, then move my mouse over "Peru", then I move mouse outside of autocomplete list , the Peru still has background color and stays selected (it should not be) . When I click anywhere on page , "Peru" is filled in...

Search Automatically

Hi man,

Great work! Is it possible to search automatically after the visitors select an option from the drop down?

Thanks :)

Highlight parts of searchstring

Hi there,
i'm using autocomplete with a serviceUrl and a backend, which retuns all results where the entered searchstring words are included
for example:
searchstring: "this sparta"
resutls are: "this vintage sparta","this sparta" etc...

the problem is that only the second result is highlighted.
Is there a solution to highlight all words in the searchstring in the results (here also "this" and "sparta" in the first resutlt)?

btw thansk for the very nice addon ๐Ÿ‘

Dynamic request URLs

Hi,

my API requires the query in the url, e.g.

/search/{query}

// the requests look like this
/search/t
/search/ta
/search/tax
/search/taxi

It would be great if there is a better way to create a dynamic url. Could be done in the onSearchStart function. Currently I do it in this way:

var serviceUrl = 'http://' + window.config.loaders.host + window.config.loaders.base + window.config.loaders.search + '/';
input.autocomplete({
    onSearchStart: function(e) {
        var instance = input.data('autocomplete');
        instance.options.params = '';
        instance.options.serviceUrl = serviceUrl + input.val();
        input.data('autocomplete',instance);
   },
   onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
   }
});

Update
btw: nice plugin, love the minimalistic approach, no big style presets and requirements (y)

add class "selected" to the item when selecting item with keyboard

Precondition:

  1. jquery - v1.9.1
  2. plugin - version 1.2.4
  3. google-chrome on ubuntu 12.04

Steps:

  1. make sure autosuggestions list appeared
  2. navigae through autosuggest options with keyboard "up", "down" keys

Result:
There is no visual indication of current autosuggest item. Such indication appears only if navigating through suggestions with mouse.

Expected:
There is an visual indication

First entry is automatically selected

First let me say thanks for this great addon.
Just updated to the latest version 1.15 and now the first entry is automatically selected when entering some chars. So when I press return, the first item is used and I cannot search for "wat", if the first item is "watch".

Option to remove the element

The component breaks if the autocomplete method is called twice on the same element and there is no way of removing it before adding it for the second time.

autocomplete

CSS?

Where is the CSS file?

onSearchStart could control if the ajax call will be done or not

I using autocomplete for a state/city choose. The user must choose the state and then fill the city.

I don't want to force him to fill the state before the city, too burocratic, but if I don't have an state, it would be good to even don't make the ajax request.

I could do it by using the onSearchStart return value. If true, I would block the ajax call, false (the default) will let the ajax be executed.

What do you think about it?

Doesn't show suggestion with ' char

I'm experiencing a strange behaviour when I put the single quote char in an autocomplete text field: json suggestions array is correctly returned with right terms, but they don't show up in the select.
If you wanna make a test, just try it on

http://offertedilavoro.it

(sorry it's not multilingual). Click on the second input field ("Scrivi comune, provincia o regione") and start typing "l'aquila" (the minChars parameter is set to 2).
Using firebug (for example), you can see that the ajax request goes forth and back with the right results, but the input fields doesn't show the suggestion.

Thanks, Daniele.

Error in makeUrl function

There is an error in the makeUrl function, it references this.options.url, it should reference this.options.serviceUrl:

    $.Autocompleter.prototype.makeUrl = function(param) {
        var self = this;
        var url = this.options.serviceUrl;
        var params = $.extend({}, this.options.extraParams);

        if (this.options.queryParamName === false) {
            url += encodeURIComponent(param);
        } else {
            params[this.options.queryParamName] = param;
        }

        return makeUrl(url, params);
    };

Match string everywhere

Hello, it should be good to match a string everywhere in the autocompletion list.

For example, i've got a field which represents people so i have in my database users named like : 'My Name'

But actually, you can match only on 'My' and not on 'Name' unless you typed 'My ' before.

I looked at the code and i found that you just have to replace line 246 :

if (val.toLowerCase().indexOf(q) === 0) {

By something like

if (val.toLowerCase().indexOf(q) >= 0) {

I think it would be nicer to make such a config variable to this functionnality

Regards,
Masadow

Hints corresponding with the text right from the start

Hi,

I like your jQuery-Autocomplete but I would find very useful if it was possible to add an option, in which hints would appear only if the first letters of the words match.
Now when I type first letter into the input, all the words that contain my letter will appear, but I need that only words starting at that letter would appear.

For example:
I am starting typing 'ne'.. and Maine would appear just because it contains 'ne' but I need that only Nebraska, New Hampshire, New Jersey, New Mexico and so on would appear..

I hope you get me.

Is it possible to add this little amendment??
I would really appreciate this.

Thanks.

Not givin any data to show

Everything works except that the plugin is not showing any back

The json data returned are correct but the plugin is not showing any back

suggestions???

Search Automatically

Thanks for your reply tkirda! appreciate it.
Regarding to: #68

hmm I still cant make it works...... can you give me some more help please :(
Basically it is either the drop down menu cant even load or it has no response at all.

I must be missing something....

I integrated the same code from the download into my project -- the suggestions box gets displayed beneath all other content in my page -- it appears to be appended to the last div in my markup, rather than just beneath my control. Any ideas?

Matching data in the middle of the word

I would like to be able to match search terms based on the start of each word in the string, but the search currently picks up matching letters in the middle of words. For instance, when searching a short local array of album names, if I enter 'in', it matches 'incunabula' and 'run into shadows' as it should, but also matches 'fresh fruit for rottINg vegetables'. If I alter line 342, changing value.toLowerCase().indexOf(q) back to ===0 (as referenced in this issue: #1 (reference)), it only matches 'incunabula' but not 'run into shadows'. Is there a value there that will work as intended? I noticed that another site that uses this plugin achieves that effect (bisonoffice.com) but I'm not clear on how. Thanks!

problem with format of json data when ajax call

Hi,

in your doc you says the ajax call must return JSON data in the following format
{
query:'Li',
suggestions:['Liberia', 'Libyan Arab Jamahiriya', 'Liechtenstein', 'Lithuania'],
data:['LR', 'LY', 'LI', 'LT']
}

i don't know if you change something but it doesn't work me. The following format work for me :

{"query":"Li",
"suggestions":[{"value":"Liberia","data":"LR"},{"value":"'Libyan Arab Jamahiriya","data":"LY"}]
}

NB I use the 1.2.5 version

Does i miss something ? or is this a little bug in the doc ?

Sincerly

Thanks for you great job.

Kspal

Dealing with case insensitive searches

I'm working on an application where all suggestions on the server side are capitalized and I want to always display them correctly on the autocomplete list. However, I would also like to allow users not to worry about lower or upper case when typing - preferably automatically making any necessary corrections as the user types. I realized it's not enough to make my database queries case insensitive on the backend, since the suggestions list only gets displayed if there's a case sensitive match with the originally typed word. Is there any way to get this working with the current code? Thanks in advance.

Remote Data Issue (Possible Bug?)

In PHP Server Side i have just some dummy data which is built like this.

        $return_arr = array();
        foreach ($locations as $row)
        {
            $return_arr[] = array(
                        'value' => $row->name,
                        'data'  => $row->id
                        );

        }

        return json_encode(array('suggestions' => $return_arr));

It results in console.log:

{"suggestions":[{"value":"Stripes #2220","data":20},{"value":"Fill Zone #50","data":21},{"value":"Circle K #5147","data":25},{"value":"IGA Express Parkway Shell","data":3849}, etc etc etc.....

Everything seems to work flawless however in the source code:

 // Display suggestions only if returned query matches current value:
 if (response.query === this.getQuery(this.currentValue)) {
     this.suggestions = response.suggestions;
     this.suggest();
 }

response.query is undefined... and console.log(response) outputs
xza

no where in the documentation does it say that i need to respond back with the 'query' in the array somewhere... any ideas?

Detect when the input value changed if the user clicked a suggestion or not

Is there a built-in way to detect, when the input changes, whether the user clicked a suggestion or not?

I looked at the code and i found the field value is set before calling the onSelect callback.

            //...
    select: function (i) {
        var selectedValue, f;
        selectedValue = this.suggestions[i];
        if (selectedValue) {
            this.el.val(selectedValue);
            if (this.options.autoSubmit) {
                f = this.el.parents('form');
                if (f.length > 0) { f.get(0).submit(); }
            }
            this.ignoreValueChange = true;
            this.hide();
            this.onSelect(i);
        }
    },
           //...

If the onSelect is called before the this.el.val(selectedValue) one would easily detect if the user selected a suggestion on change doing something like this:

$('.autocomplete').autocomplete({
    serviceUrl : '/ajax/autocomplete',
    onSelect : function(value, data, input)
    {
        input.data('suggestionClicked', true);
    }
});

$('.autocomplete').change(function(){
    if($(this).data('suggestionClicked')
    {
          // ...
    }
});

Please let me know if there's a built-in proper way to do so

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.