commadelimited / autocomplete.js Goto Github PK
View Code? Open in Web Editor NEWA jQuery Mobile autocomplete plugin
Home Page: andymatthews.net/code/autocomplete/
License: GNU General Public License v2.0
A jQuery Mobile autocomplete plugin
Home Page: andymatthews.net/code/autocomplete/
License: GNU General Public License v2.0
I did this little modification to limit the elements on proposal result lists.
var defaults = {
[...]
maxItems: 0 //all items
}
change this:
if ($.isArray(str)) {
str = str.join('');
}
for this:
if ($.isArray(str)) {
if(settings.maxItems > 0)
str.splice(settings.maxItems,str.length-settings.maxItems);
str = str.join('');
}
I'm getting an error when testing in IE 8 and IE 7. See attached screenshot for actual error message when using IE Tester and opening up an IE 8 browser.
I'm getting the error on the following demo pages: http://andymatthews.net/code/autocomplete/callback.html and http://andymatthews.net/code/autocomplete/callback-plus.html.
it only search labels start from what i type. how can it change to even search from middle or end (%term%)
It would be nice to allow custom rendering of list item, many webservices don't provide a properlly formatted json and the ability to change "label" to "name" or "whatever", would make this a very simple process. So by default it looks for "label" and optionally it allows other fields to be the label.
$("#textinput2").autocomplete({
target: $('#suggestions'),
source: jsData,
label:"name",
minLength: 1
});
Hi,
From a complex data source, I have constructed the {value, label}. The callback gets called when user chooses an item. In the callback, the label can be accessed as $a.text(). How can we access the value?
Thanks,
Yash
Not sure if you'd like this to be added back to the main project, but another modification I made to my local copy was adding the ability for the developer to have outstanding ajax requests to be stopped when a new request is made. For a while I had issues with a slow results page (which fortunately is now fixed) that would sometimes make it so the last call made wasn't always the last one returned. This resulted in the most refined results getting overwritten by a previous search.
The code is written such that if multiple autocomplete widgets are present on a page, it only stops the outstanding requests for the widget you are working with, if multiple widgets have outstanding requests.
Anyway, lemme know if you'd like me to post the code.
Hi guys,
good job - autocomplete is a great plugin!
I tried with several browsers and found some issues. You can reproduce them in your example http://andymatthews.net/code/autocomplete/
Regards
Danny
In looking over the demo page at http://andymatthews.net/code/autocomplete/, it doesn't look like IE8 (Windows) is running the autocomplete at all. I'd LOVE to be using this plugin for some projects at work, though sadly we're still required to use IE8... I'm happy to help get it up to speed in IE8 though. If you have any ideas as to why it may not be working in IE8, let me know such that I can start looking into it myself as well. Thanks!
I suggest this plugin should clear the listview whenever the 'x' in the search input gets clicked.
Using the following code, I can get #trad-suggestions to populate when i type into #input-trade (a jQM "search" input. I've also tried "text" input). The problem is the list does not update as i continue typing as in Andy's examples: http://andymatthews.net/code/autocomplete/
Data from "source" is a simple array: ["plumber","drywall","electrician"]
From what I gather, the "source" is queried once on initial keypress to acquire my array, and then handledata() applies a regular expression to modify that array on each successive keypress. If that's the case, then that regular expression is not getting applied.
If I trace the code with Chrome's Developer Tool, I see that when "source" is not an array initially, then an ajax request is made. However, if the "source" url doesn't allow sending a query string (how do we set {term : text } in the ajax "data" parameter?) then we're going to get the same array back from the serverside every time we make a query, this causing # trade-suggestions to always have the same list.
$("#input-trade").autocomplete({
method: 'GET', // allows POST as well
icon: 'wrench', // option to specify icon
target: $('#trade-suggestions'), // the listview to receive results
source: '../trades.php', // URL return JSON data
minLength: 1,
link: "",
callback: function(e) {
var
$('#input-trade').val($a.text()); // place the value of the selection into the search box
$("#input-trade").autocomplete('clear'); // clear the listview
}, // optional callback function fires upon result selection
matchFromStart: false // search from start, or anywhere in the string
});
I have an autocomplete implemented with jQuery UI autocomplete on our desktop site.. I now working on a mobile version but would like not to introduce massive jQuery UI into it.. I found your alternative but is missing a couple of features.
I have a datasource that don't returns objects with value and label properties. It returns 5 properties which I use the decide what and how it is shown in the list. This I solve in jQuery UI by overridding _renderItem.
When an item is selected I access the 5 properties again and updates 3 different form fields with a "select" function. This select function resembles your callback but an ui object is passed to it containing the 5 properties. Unsure if and how I would be able to save and access those given a _renderItem function in your plugin. Could it be through the $(e.currentTarget) object?
My jQuery UI code from the desktop site:
$('#destination').autocomplete({
source: '',
minLength: 3,
appendTo: '#autocomplete',
cache: true,
select: function( event, ui ) {
if (ui.item.LID != null) {
console.log('LID:'+ui.item.LID);
$('#navn').val('');
$('#destination').val(ui.item.LN);
$('#regionId').val(ui.item.RID);
$('#lokalOmraadeId').val(ui.item.LID);
}
else if (ui.item.RID != null) {
console.log('RID:'+ui.item.RID);
$('#navn').val('');
$('#destination').val(ui.item.RN);
$('#regionId').val(ui.item.RID);
$('#lokalOmraadeId').val('');
}
else {
TOjQ('#navn').val(ui.item.FN);
TOjQ('#destination').val(ui.item.FN);
$('#regionId').val('23');
$('#lokalOmraadeId').val('');
}
return false;
}
}).data( "autocomplete" )._renderItem = function( ul, item ) {
var text;
if (item.LID != null) {
text= '<span class="omraade">omraade</span>' + ' ' + item.LN + ' / ' + item.RN;
}
else if (item.RID != null) {
text= '<span class="region">region</span>' + ' ' + item.RN;
}
else {
text = '<span class=" + item.BN.toLowerCase() + '">' + item.BN + '</span>' + ' ' + item.FN + (item.ID != '' ? ', '+ item.BY : '');
}
return TOjQ( "<li></li>" )
.data( "item.autocomplete", item )
.append( '<a>' + text + '</a>' )
.appendTo( ul );
};
});
Is there a way available to add input parameters to an ajax service call?
Here is a sample c# service:
[OperationContract]
[WebInvoke(Method = "POST", RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, ResponseFormat = WebMessageFormat.Json)]
public List GetStates(string y)
{
List x= GetData(y);
return x;
}
Client call:
//WHERE DO I PUT INPUT PARAMETERS??
$("#searchBox").autocomplete({
method: 'POST',
target: $('#suggestions'),
source: "ClientService.svc/REST/GetStates",
link: 'target.html?term=',
minLength: 1
});
Hi,
I noticed something weird with autoComplete (v 1.4.1) and Safari on iOS 5.1 :
When I try to get the "href" value of clicked item in callback, I get "#". But it works perfectly fine with desktop browsers. Any idea ? Am I missing something ?
myInput.autocomplete({
target: $('#suggestions'),
source: function(request, response){
// api call returning JSON
response(returned_json);
},
callback: function (e) {
var link = $(e.currentTarget);
var href = link.attr('href'); // returns "#"
},
link: '?id=',
minLength: 3
});
The fix for issue #56 broke interval delayed search.
When a search is delayed because of an interval, first the current text is stored as settings._lastText
, then a timeout is set to execute handleInput
later. However, that later execution will not fire an ajax request because settings._lastText === text
.
Furthermore, interval's documentation should mention it's supposed to be in milliseconds.
Thank you for this plugin by the way, it's very useful.
I'm using socket.io and node.js. I have it set up so that with each keystroke, I make a request, and later when I receive that request, I update the autocomplete list. However, it doesn't immediately update the autocomplete list, instead I need to wait until the next keystroke before the new items are shown.
Or maybe there's another way for me to do this? Right now I'm using an array for my autocomplete source.
Thanks!
Charlie
Hi,
First of all very nice widget, very close to what i was looking for, i had a couple of ideas if you're interested:
What do you think ?
Hello there!
I am trying to use autoComplete.js in some learning mini projects I'm building trying to understand how to program with jQuery Mobile.
I've decided to start with the callback example (http://andymatthews.net/code/autocomplete/callback.html) and I've simply copied it in an empy file and saved as html: works perfectly, of course.
So I give the code a go in one of those mini projects but if I have another page linking to a page containing the autocomplete function it stops working.
index.html ---link to --> autocomplete_page.html
I've tried various solutions but nothing seems to work.
It's surely a very silly answer but being a beginner I don't find this easy to achieve.
I've tried adding in the section of index.html and the other html page this row (calling my separate js file):
<script type="text/javascript" src="js/inserimento_movimento.js"></script>And in the file I've tried various solutions to run the code, all with bad results.
The best one, accordingly to info kindly given on the jquery mobile official forum should be:
var data = ['C', 'Clojure', 'Java', 'Scala', 'Objective-C', 'C++', 'PHP', 'C#', '(Visual) Basic', 'Python', 'Perl', 'JavaScript'];
$(document).on("pageshow", ".mypageclass", function(e) {
console.log("Code running");
$(".searchField").autocomplete({
target: $('.suggestions'),
source: data,
minLength: 1,
});
});
Still no luck: the code is not executed.
If I open the console I see:
Uncaught TypeError: Object [object Object] has no method 'autocomplete'
The code (both html and js) has been modified to try with ids or classes: same result.
If I reload the second page I get a perfectly working autocomplete.
What am I doing wrong?
Forgive the newbie's question.
I try this autocomplete script and work perfect in the browser but when i deploy the program on a device using phone gap this plugin don't work
I'd like to see if there is a way to set the Authorization request header via options in your plugin.
All of my Web API's have been migrated to use JWT security tokens to help offer better security to them. What I do in my own Ajax requests is in the beforeSend option I do this:
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'Bearer ' + token)
},
the 'token' variable contains the actual JWT.
You have an onloading option and this appears to be the most likely current way to do this, but this may not be the best way to do it either.
Can I do this now, or will this take work on your part to accommodate?
In the mean time, I've added this hack that really only works for me based on the global token variable being available. I've set this in your own 'beforeSend' function in your plugin.
jqXHR.setRequestHeader('Authorization', 'Bearer ' + token);
In prepping my site for transition to JQM 1.4.0, I've ran across an issue.
With Firefox, when the autocomplete sequence starts, the first item in the li (whether it is 'searching'.... or what is returned) is pushed off to the right side of the screen and comes about half way up the text box that you are typing in.
With IE11 and Chrome 32, the first item in the li appears correctly below the text box you are typing in.
FWIW, I'm testing with Firefox 26.
Andy, in PR #18 you expressed interest in adding specs. I agree that specs will help out as the library is improved little by little, and the specs will help prevent regressions.
Is this still a goal of yours? Are you open to a pull request with Jasmine specs?
Hello,
This is a great plugin, but it would be useful to add a data{} section so we can pass additional parameters:
After line #22 add data: {}, ie
link: null,
data: {},
minLength: 0,
...
Change line #192
data: {},
to
data: settings.data,
Cheers Greg.
It would be good if you could add throttling when making ajax calls
Hy.
Is there an option to not to pass to the link, insted just use, store the selected list in a variable?
Hi,
I think it would be usefull to be able to pass some data to the link element. Fill data() with the object 'value' used in the loop of the buildItems
function in order to use it in the callback. I tried with the 1.4 version of jqmautocomplete, but you used a different way to fill the
Here's what I did (jqm.autocomplete-1.4.js line 35):
var lnk = $('<a href="' + settings.link + encodeURIComponent(value.value) + '" data-transition="' + settings.transition + '">' + value.label + '</a>')
.data('item_data', value)
.appendTo(li);
Is this a good idea ? What do you think ?
It works great but it seems to be of little value when the results are hidden by the virtual keyboard. Any way to solve this?
The pull request #5 is missing in V1.3. Could you add this again please?
Sorry for not issuing a pull request - I added this in line 76:
...
buildItems($this, data, settings);
} else if ($.isFunction(settings.source)) {
settings.source(text, function(data) {
buildItems($this, data, settings);
});
} else {
...
I am using this plugin as part of my mobile app code, and would like to have some kind of wild card search available.
Instead of settings.callback(e), it would be nice to have settings.callback.call(this, e)
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
it's possible put 2 autocomplete in the same page? If it's possbile How I can I do? What I need change? thanks!!
I use version 1.5.1 with remote data source to fill a city list.
When I fill input to quickly, the list is not updated with the last request.
For example when I tape "Toulou", I don't expect to have "Toulon" in result list.
In firebug I saw that it's because request for "Toulo" succeed after request for "Toulou".
The example (http://andymatthews.net/code/autocomplete/) is also not work.
Hi Andy, I'm having success getting autocomplete to respond and bringing back results from a URL, but when I bind them to my empty <ul> (like in your remote object example), the list renders as a plain old bulleted list as opposed to a styled jquery mobile listview.
Have you ever run across this problem before? I've racked my brain trying to understand why this would happen... Thanks for any insights/ideas.
Hi!
Auto complete is working, but after clicking the result linked to the same page and than back to the search page, automatch isn't working anymore.
$("#search_input").autocomplete({
target: $('#suggestions'),
source: autocompleteData,
link: 'add_date.php?date=&id=',
minLength: 1
});
if (ISSET($_GET["id"])){
some code here...
header("location:add_date.php?date=$datum");
die;
}
Hi there,
first of all thanks for sharing your great code.
It would also be nice if we could have the option of displaying a drop down arrow to the right of the component, so that the user can click to get all options, e.g. in case there are only a few. This will also give a "combobox" feeling to the user.
Thanks again.
Regards
I really like your autocomplete.js widget. Can you please guide me to install on my website. I want to use it on my main website and mobile website. How can I install it? My web address is www.pharmacyexam.com Any help would be greatly appreciated...
If I set the minlength to 1 and writes "This is a test" your autocomplete fires 14 ajax calls.
jQuery UI's autocomplete operates with a delay to allow the user to finish the typing.. I would like to see this in your autocomplete too as the ajax calls are expensive on the mobile data connections..
Another thing is that jQuery UI's autocomplete cancels old ajax calls if a new one is fired. I guess this saves bandwidth too.
Hello,
i use your autoComplete.js for a list of IT competences. One is C/C++.
If I type C++ i get this error on my console :
Uncaught SyntaxError: Invalid regular expression: /c++/: Nothing to repeat
jqm.autoComplete-1.4.3-min.js:10
I guess an encodeURIComponent would make it.
Great plugin by the way :)
iFox
I have a data source of nested objects. I need to be able to search through this source and return results that are nested, and I'm hitting a wall. I was hoping you could help me out. Here's my JSON and the buildList function that I've edited:
JSON:
[
{
"label": "sitegroup1",
"children":
[
{
"label": "site1",
"children":
[
{"label": "datasource1", "datasourceid":99},
{"label":"datasource2","datasourceid":13}
]
}
]
}
}
And buildList function:
buildItems = function($this, data, settings) {
var str = [];
$.each(data, function(index, value) {
// are we working with objects or strings?
if ($.isPlainObject(value)) {
//if(value.datasourceid){
str.push('
The commented out code is what I've done myself. If you could help me out here I'd be very grateful!
What would be the best way to clear the listview when focus is lost?
I suppose I could set an on click on the parent div and detect if the target is not 'ui-link-inherit' and then run an autocomplete('clear') method on all my input fields? This doesn't seem very efficient however.
Any thoughts?
It s happens that you are looking for label and value in a complex data json structure. our api returns value in the format
[
{id: 123, name: "ABC"},
{id: 133, name: "XYZ"}
]
obviously this does not work.
It would be great if you could let us control, how to transform this data to the format you require. It would help instead of changing code in the API (may be some who does noth ave access to the API code, might feel good)
I'm using this plugin to lookup an account name, and would like the account ID to be placed into another text field. I see how to refer to the text in the callback function. How do I refer to the ID number? If this function is not currently available, I'd sure love to see the feature added. This is a great plugin, and I will be able to use it widely if it functioned this way.
(Sorry if I'm not submitting this properly--I'm a Github n00b.)
Thanks!
Jay
Just attached autocomplete to a search input box.
When I clear the search text manually, the target listviev is cleared as expected but if clicking the ‘clear button’ from the search box, the list target is not cleared?
Ming
When I try to use this plugin with python-turbgears backend, my server side application do not permit me to return array as json.
Module tg.controllers.decoratedcontroller:265 in _render_response view
'You may not expose with JSON a list return value because'
JsonEncodeError: You may not expose with JSON a list return value because it leaves your application open to CSRF attacks.
I can return json from server like this:
{data: [
{
value: "22",
label: "Maine"
},
{
value: "23",
label: "Maryland"
}
]
}
Jquery implementation of autocomplete is ok with this return data so I've look at the code and done a quick fix:
line 200 of jqm.autoComplete-1.5.0.js, I've changed
buildItems($this, data, settings);
to
buildItems($this, data.data, settings);
and the new code looks like this:
var ajax = {
type: settings.method,
data: {},
dataType: 'json',
beforeSend: function(jqXHR) {
if (settings.cancelRequests) {
if (openXHR[id]) {
// If we have an open XML HTTP Request for this autoComplete ID, abort it
openXHR[id].abort();
} else {
}
// Set this request to the open XML HTTP Request list for this ID
openXHR[id] = jqXHR;
}
if (settings.onLoading && settings.onLoadingFinished) {
settings.onLoading();
}
if (settings.loadingHtml) {
// Set a loading indicator as a temporary stop-gap to the response time issue
settings.target.html(settings.loadingHtml).listview('refresh');
settings.target.closest("fieldset").addClass("ui-search-active");
}
},
success: function(data) {
buildItems($this, data.data, settings);
},
complete: function () {
// Clear this ID's open XML HTTP Request from the list
if (settings.cancelRequests) {
openXHR[id] = null;
}
if (settings.onLoadingFinished) {
settings.onLoadingFinished();
}
}
Maybe there should be a optional parameter to use this autocomplete plugin for pythonistas like me. :)
Would you happen to have an example of how I could use your autocomplete with a MySQL database?
I have JSON results with links like this:
[
{
"label": "<img src=\"/asset/styles/images/producer/producer-80x80.png\" alt=\"\"/><h4 class=\"producer-title\">Josef Dockner </h4><p class=\"region\">Kremstal, Österreich</p><p class=\"extra table\">Gartensaal, Tisch 11</p>",
"value": "/de/event/vievinum12/producer/p.adccccfbd66c8e19c123df26e2842380/"
}, {
"label": "<img src=\"/static/p.d0fa187b7c287e99ae5c2b8bc475a0ed/thumb80x80.jpg\" alt=\"\"/><h4 class=\"producer-title\">Tom Dockner <span class=\"uw-premium-producer ui-icon ui-icon-star\" title=\"Premiumwinzer\"></span></h4><p class=\"region\">Traisental, Österreich</p><p class=\"extra table\">Vorsaal, Tisch 151</p>",
"value": "/de/event/vievinum12/producer/p.d0fa187b7c287e99ae5c2b8bc475a0ed/"
}
]
To make this work, I changed lines 27 and 29 to use encodeURI instead of encodeURIComponent;
if ($.isPlainObject(value)) {
str.push('<li><a href="' + settings.link + encodeURI(value.value) + '" data-transition="' + settings.transition + '">' + value.label + '</a></li>');
} else {
str.push('<li><a href="' + settings.link + encodeURI(value) + '" data-transition="' + settings.transition + '">' + value + '</a></li>');
}
Sorry for the mess - next time I'll issue a pull request, I promise! ;-)
Hello,
this is a feature request.
I'd love to benefit from this plugin to make a "search" feature.
I have "complex" listview items representing objects (let's say a wine) with different attributes (name, producer, grape type, etc.)
I'd like
I think a 'template' parameter could do the trick with a simple tokens to replace with values from the json data.
what do you think?
The newest version (1.5.0) doesn't seem to work to in IE8 or IE7. The problem also occurs in the example.
I think the problem is with Date.now, which doesn't exist before IE9. The following code fixes this:
if (!Date.now) {
Date.now = function() {
return new Date().valueOf();
}
}
Found it on http://blog.yjl.im/2012/01/datenow-in-ie8-or-before-ie9.html
When page loads with filename.html?term=17
I cant get to the value of term on next page, without refreshing the url.
I have tried this, but it doesn't work: (using rel="external" data-ajax="false")
ul id="suggestions" data-role="listview" data-inset="true" data-theme="c" rel="external" data-ajax="false"
So I was going to use a call back function, but cant figure out how to get to the value.
Any help would be much appreciated. Thanks!
Autocomplete seems not to work properly when target container is generated by script (not have been loaded initially)
In version 1.4.3 the problem appeared as disability to remove suggestions list.
Example (remember to remove spaces on html):
$(".sym_suggest").live("focus", function(){
$(this).val("");
if($(this).data("AC_ass") != undefined){return;}
var rnode = Math.random().toString().split(".")[1];
$(this).after('< ul id="'+rnode+'" data-role="listview" data-inset="true" >< /ul >');
$("ul#"+rnode).listview();
$(this).autocomplete({
link: "#",
target: "ul#"+rnode,
source: 'async/suggest.htm?agegender=',
callback: function(e) {
var a = $(e.currentTarget);
$("ul#"+rnode).html("");//this added because .autocomplete('clear').val("") not working
$(this).autocomplete('clear').val("");
console.log(a.attr("href").substr(1), a.text());
},
minLength: 2
});
});
And html is:
< input type="text" class="sym_suggest" />
note that there's no static target container
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.