Example of Autocomplete in jQuery Mobile

This post is more than 2 years old.

A while back a reader (Bobby Tuck) asked me about how to do autocomplete in a jQuery Mobile application. He tried using jQuery UI's autocomplete control but found it didn't integrate well on a mobile device with the keyboard popped up. I suggested an alternative and (finally!) got around to building a mockup. Here's my take on it - feel free to rip it apart and suggest alternatives and improvements.

Let's begin with a simple jQuery Mobile template.


<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>

<body>

<div data-role="page" id="mainPage">

	<div data-role="header">
		<h1>Autocomplete Example</h1>
	</div>

	<div data-role="content">

		<p>
		<input type="text" id="searchField" placeholder="Search">
		</p>

	</div>

	<div data-role="footer">
		<h4></h4>
	</div>

</div>

<script>
$("#mainPage").on("pageshow", function(e) {
	console.log("Ready to bring the awesome.");

});
</script>

</body>
</html>

I've got a few things going on here to prepare for the autocomplete control. I've got a text field that will accept the user input. I've got a page event handler (this is jQuery Mobile specific) that will fire when the page loads. Now let's talk about my proposed solution.

I thought it might be handy to use a jQuery Mobile listview to render the suggestions. So I began by adding an empty list view beneath my form field:


<p>
<input type="text" id="searchField" placeholder="Search">
<ul id="suggestions" data-role="listview" data-inset="true"></ul>
</p>

I then wrote some simple code to handle changes to the input field.


$("#mainPage").on("pageshow", function(e) {
	console.log("Ready to bring the awesome.");
	var sugList = $("#suggestions");

	$("#searchField").on("input", function(e) {
		var text = $(this).val();
		if(text.length < 1) {
			sugList.html("");
			sugList.listview("refresh");
		} else {
			$.get("service.cfc?method=getSuggestions", {search:text}, function(res,code) {
				var str = "";
				for(var i=0, len=res.length; i<len; i++) {
					str += "<li>"+res[i]+"</li>";
				}
				sugList.html(str);
				sugList.listview("refresh");
				console.dir(res);
			},"json");
		}
	});

});

The code is rather simple I think. We bind to the "input" event for the text field and check the value. Now - most autosuggest controls make a determination on whether or not it makes sense to fire off a request. You may - for example - decide you only want to ask for autocomplete results when the user has entered 3 or 4 characters. Mine will always fire as long as you have at least one character. I did that because my data (a list of names) was a bit short and I wanted to ensure that the demo was easy to use. Obviously you can alter that to your liking.

If the user entered something, we fire off a request to the server. (In this case to a ColdFusion script that performs a search against a list of names. It's trivial enough that I won't include it in this blog entry, but if anyone wants it, you can view it here: http://pastebin.com/pFGggRc3) The server responds with an array of names. We can then take that array and create a simple HTML string out of it. This string is inserted into our empty list and then we simply call the jQuery Mobile refresh method to ensure it is marked up correctly.

And that's it. I tested it on my mobile device and while the keyboard will cover some of the results, it seems to work well:

Obviously this demo needs a bit more work to be complete. Your list options would probably link to the detail for your search results. You can find the demo below as well as the complete code.

Demo is removed as I no longer run ColdFusion on my server. Here is a link to a zip: https://static.raymondcamden.com/enclosures/27.zip


<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Example</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/latest/jquery.mobile.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/latest/jquery.mobile.min.js"></script>
</head>

<body>

<div data-role="page" id="mainPage">

	<div data-role="header">
		<h1>Autocomplete Example</h1>
	</div>

	<div data-role="content">

		<p>
		<input type="text" id="searchField" placeholder="Search">
		<ul id="suggestions" data-role="listview" data-inset="true"></ul>
		</p>

	</div>

	<div data-role="footer">
		<h4></h4>
	</div>

</div>

<script>
$("#mainPage").on("pageshow", function(e) {
	console.log("Ready to bring the awesome.");
	var sugList = $("#suggestions");

	$("#searchField").on("input", function(e) {
		var text = $(this).val();
		if(text.length < 1) {
			sugList.html("");
			sugList.listview("refresh");
		} else {
			$.get("service.cfc?method=getSuggestions", {search:text}, function(res,code) {
				var str = "";
				for(var i=0, len=res.length; i<len; i++) {
					str += "<li>"+res[i]+"</li>";
				}
				sugList.html(str);
				sugList.listview("refresh");
				console.dir(res);
			},"json");
		}
	});

});
</script>

</body>
</html>

P.S. So hey - what about the HTML5 Datalist option? Unfortunately on mobile it is only supported in Opera. You can find details on support here: http://caniuse.com/#feat=datalist

Raymond Camden's Picture

About Raymond Camden

Raymond is a senior developer evangelist for Adobe. He focuses on document services, JavaScript, and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support. You can even buy me a coffee!

Lafayette, LA https://www.raymondcamden.com

Archived Comments

Comment 1 by Simon posted on 3/27/2012 at 9:34 PM

Couldn't pick of the drop down list on iPod touch iOS 5 which I'm guessing is the same as an iPhone

Comment 2 by Raymond Camden posted on 3/27/2012 at 10:08 PM

Simon, did you read the post? That was intentional. I mentioned that in a real app you would link the results to something.

Comment 3 by Mike posted on 3/28/2012 at 2:22 AM

Would it be possible to user your example but search in a list or from csv file?

Comment 4 by Raymond Camden posted on 3/28/2012 at 5:57 AM

Yes. Definitely possible.

Also - to all - Andy Mathews turned this concept into an even easier to use plugin: http://www.andymatthews.net...

Comment 5 by Gareth Arch posted on 3/28/2012 at 6:46 AM

This is the way I've handled it in my Mobile AIR apps also. Running a filter on the dataprovider of a list element.

Comment 6 by Raymond Camden posted on 3/28/2012 at 6:48 AM

Nice - I knew that time I spent learning Flex wasn't a waste. :)

Comment 7 by quickfix posted on 5/21/2012 at 6:53 PM

Hi, I successfully used Andy Mathews's plugin for autocompletion in my jquery mobile app using a input type="search" field.
It works very well in browsers (both desktop and android) but when I package my app with phonegap for android, there is a kind of history (or suggestions) div under my input field that partially hides my results div.
Have you ever encountered this and/or know how to disable it? (I've tried few webkit tricks with no success)

Comment 8 by Raymond Camden posted on 5/21/2012 at 6:55 PM

Try adding this to the form field:

autocomplete="off"

Comment 9 by quickfix posted on 5/21/2012 at 8:14 PM

that's part of the "webkit tricks" I had already tried.
I've inspected the page with weinre and was not able to find the div.
Actually I realised that it does not appear under my input but in the middle of the screen so I thought it had something to do with the virtual keyboard.
I ended with renaming the name of my input (was "immatriculation") and now I don't see the nasty div anymore.
Weird, but I don't think I'll dig deeper for the moment...

Comment 10 by Amit posted on 5/29/2012 at 3:58 PM

Please Give Me Remember password coding using phonegap..

localstorag will work in single page next page it not show the in case of this windows.localstorage(key,value);

Comment 11 by Raymond Camden posted on 5/29/2012 at 5:45 PM

Amit, I appreciate you want help on this, but I'm not going to write the code for you. Localstorage is per domain, not per page. It will work fine in PhoneGap. It is -very- trivial to use.

Comment 12 by Gareth Arch posted on 5/29/2012 at 5:54 PM
Comment 13 by Matthew Reinbold posted on 7/9/2012 at 7:47 AM

Playing around with this and Andy Mathews' code tonight.

What I've done is put the search bar in the footer. It works great the first time a page is loaded. However, if I click on one of the search results and go to a different page, the search autocomplete doesn't work.

There's no console errors. Inspecting the page shows the javascript still present but only listed under the original page (I'm using the single rather than multi-page jquery mobile model, but jquery is "pushing" pages to a stack in case I go back???).

If I hard refresh the page the autocomplete works - until I click to a different page, then it is broke again.

I rewrote the jQuery selector to be page sensitive, like:

$("div[data-role='page']").on("pageshow", function(e) {

I'm thinking its because the pageshow event isn't being fired after a transition to a different page? Any ideas why that would be?

Comment 14 by Raymond Camden posted on 7/9/2012 at 4:05 PM

To be clear, your modified version is only running once?

Comment 15 by Matthew Reinbold posted on 7/9/2012 at 7:31 PM

It appears that way (added a console logging statement to output the page div id to make sure).

On first load (or hard refresh) my console logs that I'm on the page and jquery attaches autocomplete to the search input. If I click a link jquery transitions to the next page. Despite having set this to have a fresh call to the server for the new page, the js to attach the autocomplete attachment never fires again.

Inspecting the page I see that previous page content is appended to the body of the document. The script for attaching the autocomplete is present there but not in the newly loaded page div.

Comment 16 by Raymond Camden posted on 7/9/2012 at 8:26 PM

I assume your other pages use <div data-role="page">, right? Perhaps you can share some more code via pastebin.

Comment 17 by Matthew Reinbold posted on 7/9/2012 at 8:34 PM

Yes, I am using <div data-role="page" >

Ultimately, the only way I've been able to make this work with the search in the footer is to disable the jQuery mobile transitions. I've had to add "data-ajax='false'" to every single link (pain in the rear) in order to keep jQuery mobile from grabbing the desired page, parsing it to look for only the inner page content, and not execute the autocomplete hookup.

In jQuery mobile 1.1 you're SUPPOSED to be able to add "data-ajax='false'" to a container have it apply to all child elements. Despite using 1.1, however, I haven't been able to get this to work; http://jquerymobile.com/tes...

Comment 18 by Raymond Camden posted on 7/9/2012 at 8:35 PM

Question - did you keep my console.log msg in - and did it show but the autosuggest not work?

Comment 19 by Matthew Reinbold posted on 7/9/2012 at 9:42 PM

Yes. The console.log works - on the first document request. Subsequent document requests do not cause the javascript to be run again when it is inside a data-role="footer" div. That is, until I turned off the data-ajax="false".

Comment 20 by Raymond Camden posted on 7/9/2012 at 9:49 PM

You mentioned you were using the field in the footer, right? If so, did you switch from an ID to a class based form field?

$("#searchField").on("input", function(e)

to

$(".searchField").on("input", function(e) {

and obviously removing id=".." from the field and using class=".." instead.

Comment 21 by Matthew Reinbold posted on 7/10/2012 at 7:18 AM

I had been accounting for the different divs on the search field. However, while double checking that I had one of those faceplam moments: I had left the results div id (the #suggestions data-role listview) the same.

Duh. Although the exercise has been a good one and forced me to dig into how jQuery Mobile 'caches' pages.

Comment 22 by Raymond Camden posted on 7/10/2012 at 5:03 PM

I'm just glad you figured it out.

Comment 23 by Lasane.In posted on 8/27/2012 at 7:06 PM

Nice And step By Step Tutorial. Thanks

Comment 24 by al posted on 9/18/2012 at 11:25 PM

I am using Andy Mathews' code with aspx page for data. It returns array of strings, but final result is only one letter on one line. Here is the code What should be after success?
$("#searchField").autocomplete({
target: $('#suggestions'),
source:
function (request, response) {
$.ajax({
type: "POST",
url: "search.aspx/GetSearch",
data: "{search:'" + $("#searchField").val() + "'}", // passing value of txtSearch input
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {

response(data.d, function (item) {
// alert(data.d);
return { value: item.name
}
});
},
failure: function (response) {
alert("Issues Here");
}
});
},
link: 'target.html?term=',
minLength: 1,
transition: 'slide'
//matchFromStart: false
});
});
Thanks

Comment 25 by Raymond Camden posted on 9/19/2012 at 1:06 AM

I'd recommend filing an issue on Andy's page (https://github.com/commadel... since his code is going to be different than mine, and a bit off topic for this blog post.

Comment 26 by Andrea Rocca posted on 10/26/2012 at 4:18 PM

the min version is functionally different vs the normal version. at this point:"e.isPlainObject(n)?s.push("

Comment 27 by Raymond Camden posted on 10/26/2012 at 4:31 PM

Andrea, if you are talking about an issue with jQuery Mobile, I'd recommend filing a bug report at their site.

Comment 28 by AKBAR posted on 11/2/2012 at 2:57 PM

Not working in mozilla and chrome.

Comment 29 by Raymond Camden posted on 11/2/2012 at 2:59 PM

*How* ia it not working? What do you see in the remote debugging console? I assume you mean Chrome and Firefox for Mobile.

Comment 30 by Albert posted on 11/6/2012 at 9:33 PM

hey there!

thanks for the tutorial! i'm playing around with jquerymobile atm and found this very helpful and it works nicely. since i'm using php, here is what i did:

ajax part of your script:

$.get("example.php", {suggest: txt}, function(data) {
var str = "";
for (var i=0; i<data.length; i++) str += "<li><a href=\'some.php?show="+data[i]["id"]+"\'>"+data[i]["name"]+"</li>";
str += "<li data-theme=\'a\'><a href=\'some.php?find="+encodeURI(txt)+"\'>Search “"+txt+"”</li>";
sugList.html(str);
sugList.listview("refresh");
}, "json");

example.php:

$array = array();
$mysql = mysql_query("SELECT id, name FROM somewhere WHERE something LIKE '".mysql_real_escape_string($_GET['suggest'])."%' LIMIT 5");
while ($row = mysql_fetch_assoc($row)) $array[] = $row;
echo json_encode($array);

Comment 31 by Amanda posted on 11/21/2012 at 2:45 AM

Hi! Great tutorial...exactly what I was looking for. The .on("input" is not listening to my text box. I've tried selecting it as a class, id, and with the name. I can't seem to get it to listen. Any ideas?
Thanks!

Comment 32 by Raymond Camden posted on 11/21/2012 at 2:48 AM

Where are you testing it?

Comment 33 by Amanda posted on 11/21/2012 at 2:54 AM

Google Chrome

Comment 34 by Raymond Camden posted on 11/21/2012 at 2:55 AM

Not sure then. Is it online where I can see?

Comment 35 by Amanda posted on 11/21/2012 at 6:15 PM

No, I can't put it online right now. Thanks for your help though. Your tutorial was great!

Comment 36 by ROBERT posted on 12/7/2012 at 12:26 AM

$("#searchPage").on --> This event is not firing in IE. It gives error"object is not supported : on"

Comment 37 by Raymond Camden posted on 12/7/2012 at 12:32 AM

The on method works in recent jQuery builds. Be sure you are using the latest jQuery.

Comment 38 by ROBERT posted on 12/7/2012 at 12:34 AM

I am using asp.net mvc. Also all the jquery scripts are placed in master/layout page. Any ideas why I am receiving the above error error. I am also new to jquerymobile.

@model Title
@{

ViewBag.Title = "Search";
Layout = "~/Views/Shared/_Layout.cshtml";
}
@using (Html.BeginForm("Search", "Title", FormMethod.Post, new { id = "Form1" }))
{
<div id="searchPage">
<p>

<input type="text" id="searchField" placeholder="Search"/>
<ul id="suggestions" data-role="listview" data-insert="true"></ul>
</p>
</div>
}
<script type="text/javascript">
$("#searchPage").on("pageshow", function (e) {
debugger;
var sugList = $("#suggestions");

$("#searchField").on("input", function (e) {
var text = $(this).val();
if (text.length < 1) {
sugList.html("");
sugList.listview("refresh");
} else {
$.ajax(
{
type: "GET",
url: "http://servername:port/page/select?q=name:" + text + "&fl=name&sort=name asc",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var str = "";
for (var i = 0, len = data.length; i < len; i++) {
str += "<li>" + data[i] + "</li>";
}
sugList.html(str);
sugList.listview("refresh");
},
error: function (xhr, status, errorThrown) {
alert(errorThrown);
}

});

}
});

});
</script>

Comment 39 by Raymond Camden posted on 12/7/2012 at 12:37 AM

Please see my earlier comment. You need to ensure you are loading the latest jQuery library.

Comment 40 by ROBERT posted on 12/7/2012 at 1:37 AM

Thanks for the suggestion.
I was using the old jquery libraries.. My Bad!!
I tried using the new one but mine other screens stopped working now(giving some javascript "o.length null" error).
Is there any workaround of "on" function with old jquery libraries?

Comment 41 by Raymond Camden posted on 12/7/2012 at 1:39 AM

Yes - just use one of the older ones. live() may work. Here is the list: http://api.jquery.com/categ...

Comment 42 by ROBERT posted on 12/7/2012 at 1:52 AM

yes, live() is working.!!
Many Thanks!!

Comment 43 by hp178 posted on 12/20/2012 at 3:43 PM

Hey,

I had a query.
Suppose i want to search from a table which contains, say, around a thousand records.
Would it be easier for me to ping the database each time a key is pressed or should i bring down the whole list into my local database and then keep refining my search?
Which approach would consume less process cycles AND provide faster results?

Also what method have you used in your code?

Comment 44 by Raymond Camden posted on 12/20/2012 at 4:47 PM

I think moving the db locally has its plusses and minuses. If you move the data locally, you have to:

a) write code to do the initial seed
b) write code that, periodically, sees if there is newer data on the remote server

That isn't hard, but it isn't trivial either.

That being said, even with 1K records in your database, you only want to return a max number of matches anyway, like 50. So I'm not necessarily sure it is worth the effort to create a local copy.

Sorry I don't have a firm answer for you, but like most things, it depends.

Comment 45 by hp178 posted on 12/20/2012 at 5:41 PM

So

You mean, that if i am searching "Raymond" in my database.
When i type 'r' the plugin will search for names beginning with 'r' in the database and when i add an 'a' to it, it will search the database again for names beginning with 'ra'?

I have been using Andy Mathews plugin for my app. I am not familiar with the ColdFusion technology, therefore i have called a function as the source which returns a json object after fetching it from the database.

Is that the right way to do it?
What would I have to do, if i want to check the database every time a key is pressed and NOT get the whole database.

here is my function:

function json_function()
{
var item_list = new Kinvey.Collection('purchaseDetails1');
var data_array = new Array();
item_list.fetch({
success: function(list) {
list.forEach(function(purchase) {
data_array.push(purchase.toJSON(true));
});
alert(data_array[0].vendor_name);
},
error: function(e) {
alert(e.description);
}
});
return data_array;
}

Comment 46 by Raymond Camden posted on 12/20/2012 at 6:03 PM

"You mean, that if i am searching "Raymond" in my database.
When i type 'r' the plugin will search for names beginning with 'r' in the database and when i add an 'a' to it, it will search the database again for names beginning with 'ra'?"

Um, well, yeah, thats one way of doing an autocomplete. Typically the idea is- compare your input to a list. The list may be a database, may be a static (hard coded) list, etc. It's _some_ kind of data.

"What would I have to do, if i want to check the database every time a key is pressed and NOT get the whole database."

I'm not entirely sure I'm getting your issue here, but you would use Ajax to talk to your server middleware. For me it was ColdFusion. It could be PHP, Ruby, Node, etc. Basically, something on your server interfaces with a database.

Comment 47 by hp178 posted on 12/21/2012 at 9:48 AM

I am creating a mobile app using HTML5 and javascript. I am using the Kinvey services for the backend.
The backend is therefore on the cloud along with the backend logic.
Now if i am searching a list of 1K records, what i want is that my plugin should ping the database on press of each key rather than getting and storing the whole list in the local DB.
Which, i think, is what i am doing by getting my data into "data_array".(right???)
How do i change the code such that the 'source' is called each time a key is pressed by passing the string in the searchbox.

Comment 48 by Raymond Camden posted on 12/21/2012 at 5:34 PM

If I read you right, are you asking how to make the source remote? If so, that's what my code shows you above. You would just change the URL (assuming your result data is also an array of strings).

Comment 49 by Unmesh posted on 1/17/2013 at 4:21 PM

Is it possible to invoke a javascript function on the link attribute? i.e. when one of the items in the "suggestions" list is clicked on, make an ajax call instead of redirecting to another page.

Comment 50 by Raymond Camden posted on 1/17/2013 at 5:26 PM

Sure.

Comment 51 by Maduranga posted on 2/5/2013 at 10:10 AM

HI,
Can anyone tell me why this below code is not working in IPAD safari web browser? It worked perefectly in Chrome and Firefox but not in IPAD Safari browser.

<script type="text/javascript">

$("#mainPage").on("pageshow", function (e) {

var sugList = $("#suggestions");

$("#CustomerCode").on("input", function (e) {
var text = $(this).val();

if (text.length < 1) {
sugList.html("");
sugList.listview("refresh");
} else {
$.ajax({ cache: false,
type: 'GET',
dataType: 'json',
url: '/Lookup/GetCustomer',
data: { filterCustomerCode: text },
success: function (res, code) {
var str = "";
for (var i = 0, len = res.length; i < len; i++) {
str += '<li data-icon="arrow-r"><a href="/home/index?CustomerCode=' + res[i].Code + '" >' + res[i].Code + '</a></li>';
}
sugList.html(str);
sugList.listview("refresh");
console.dir(res);
},
async: true
});
}
});

});

</script>

Thanks,
Maduranga

Comment 52 by Raymond Camden posted on 2/5/2013 at 5:54 PM

What is the URL so I can test it?

Comment 53 by Maduranga posted on 2/6/2013 at 3:06 AM

HI Raymond,
Its not available on internet since it carries a lot of information of a company's sales. Therefore, its running on an intranet.

I am testing through a IPAD 1 and IOS 5.

Thanks,
Maduranga

Comment 54 by Raymond Camden posted on 2/6/2013 at 5:10 AM

What I'd recommend than is creating a simple version you can share - one that replicates the issue - and then share that URL.

Comment 55 by Thomas Pal Supp posted on 4/3/2013 at 9:19 PM

Hi Raymond,
Thanks a lot for your help and contribution!

I'm trying to have an autocomplete text input field as part of a form on my mobile website and I can't find any mobile example in the web.

Is there a way to make the listview clickable? so that when a user types "Wil" and clicks on the "Wilson, Maxwell" line, the value "Wilson, Maxwell" will be moved to the text input field (which will be later on submitted to the form's target page).

Thanks again,
Thomas

Comment 56 by Raymond Camden posted on 4/3/2013 at 9:49 PM

You would simply take the JS I use to generate the HTML and make it include a link.

Comment 57 by Thomas Pal Supp posted on 4/4/2013 at 12:05 AM

Yep it worked! Thanks a lot :)
Here is my work for sharing..

This is how I wrapped it with a link:
str += "<li><a href=\"javascript:somejsfunc('"+res[i]+"');\">"+res[i]+"</a></li>";

This is how I implemented autocomplete using local array res:
else {
var str = "";
for(var i=0, len=res.length; i<len; i++) {
if (Cities[i].substring(0,text_length) == text) {
str += "<li><a href=\"javascript:somejsfunc('"+res[i]+"');\">"+res[i]+"</a></li>";
}
}
sugList.html(str);
sugList.listview("refresh");
console.dir(res);
}

and this is my somejsfunc():
function somejsfunc(str) {
//first moving the chosen value to the input field
document.getElementById('input_text_field').value = str;

//second empting the suggestions' list view
sugList.html("");
sugList.listview("refresh");
};

Comment 58 by Ayotunde Ayoko posted on 4/11/2013 at 8:28 PM

Sir...I just want to say, Thank you..Thank you...Thank you for this post. It's been very helpful to me. I really appreciate this.

Comment 59 by Ruen posted on 6/5/2013 at 8:03 AM

Thank you for this :D This helped me a lot

Comment 60 by amir posted on 9/6/2013 at 11:17 PM

Hi there
Here is my php code that not working:

***************search.php :******************

<div data-role="page" id="mainPage">

<div data-role="header">
<h1>Autocomplete Example</h1>
</div>

<div data-role="content">

<p>
<input type="text" id="searchField" placeholder="Search">
<ul id="suggestions" data-role="listview" data-inset="true"></ul>
</p>

</div>

<div data-role="footer">
<h4></h4>
</div>

</div>

<script>
$("#mainPage").on("pageshow", function(e) {
console.log("Ready to bring the awesome.");
var sugList = $("#suggestions");

$("#searchField").on("input", function(e) {
var text = $(this).val();
if(text.length < 1) {
sugList.html("");
sugList.listview("refresh");
} else {
$.get("include/search2/find.php", {search:text}, function(res) {
alert(res);
var str = "";
for(var i=0, len=res.length; i<len; i++) {
str += "<li>"+res[i]+"</li>";
}
sugList.html(str);
sugList.listview("refresh");
console.dir(res);
},"json");
}
});

});
</script>

*********************find.php************************
@session_start();
if($_GET['search']){
$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/include/db/db_conn.php";
include_once $path;
$array = array();
$sql = "SELECT jid as id,name FROM jobs_tb WHERE name LIKE '%".mysql_real_escape_string($_GET['search'])."%' LIMIT 5";
$mysql = mysql_query($sql) or die(mysql_error());
echo $sql;
while ($row = mysql_fetch_assoc($mysql))

$res[] = $row;
echo json_encode($res);

Comment 61 by Raymond Camden posted on 9/6/2013 at 11:56 PM

First, please do not post large blocks of code on this blog. Second, you didn't say _how_ it wasn't working? What do you see in your browser dev tools?

Comment 62 by LB posted on 10/17/2013 at 10:26 PM

Hello,
Thank you so much for posting this... I used it to do an autocomplete on my webapp, and I'm very happy with it. One thing I'd like to do that I need help on, in the case that someone here might know...

What I want to do involves something regarding using this on a desktop browser... My issues is N/A for the mobile browsers. I know it probably makes more sense to have a separate layout for desktop browser from a mobile one, but I'd really like to have one page that serves both well.

I'd like to make it so if the user hits the down-arrow on the keyboard that it puts the focus on the first entry with the popped-up suggestion list. It actually works this way if you hit the Tab key, but I purposelessly "disabled" that... I wanted the tab-key to jump to the next field (for people that like typing everything quickly)... So I'd really like the down-arrow to put the focus on the first entry, the way the tab-key normally would (before I disabled it). I tried the following code to capture the down-arrow key and call the focus on the first entry of the suggestion list, but it doesn't work. If anyone has any suggestions, I'd appreciate.

I do this on the item build-up code:
idName = "id=\"" + fieldCurrent + "_" + index + "\" name=\"" + fieldCurrent + "_" + index + "\" tabindex=\"" + index + "\"";
str += "<li " + idName + "><a href=.... etc..
To give each item an id, name, and tabindex of 1.

I then use this from the event OnKeyDown
if (event.keyCode == 40) {
var sugList;
console.log("#" + fieldCurrent + "1")
sugList = $("#" + fieldCurrent + "1");
sugList.focus();
}

It does spit out the console message, but doesn't put focus on the first item.

On another note... I can use this code to set focus to the suggestion List as a whole itself.... but that's not what I want, because scrolling through the entries doesn't work, nor does hitting "enter" to select one work. I want the first actual entry to get the focus (just as if user had hit the tab key) so they can then scroll down to more entries or hit the Enter-key to select one.

Comment 63 by LB posted on 10/17/2013 at 11:20 PM

Disregard my previous post... I see where my mistake was.

Comment 64 by Ana posted on 10/24/2013 at 12:14 AM

Hello,
I re-created your example with php, is working perfect in the website:
http://synergyholisticdirec...
I used the same version of jquery and jquery mobile you used, but when I tested in my phone (I use phonegap 2.9) and is not showing the results! I'll appreciate a lot If anyone have any suggestion that can help me. Thanks!!!!

Comment 65 by Anber posted on 11/1/2013 at 4:34 PM

Hello. this plugin is very great, but when i use chined pinyin but it is not autocomplete on phone website, but it is useful on pc website, i think is the event on listen , can you help me ,use chinese event , thanks a lot

Comment 66 by Raymond Camden posted on 11/1/2013 at 5:54 PM

I'm sorry, but without more details I really can't help.

Comment 67 by Anber posted on 11/2/2013 at 7:53 AM

hi man , do you know the chinese input event on the mobile phone, the keyup ,and keydown is not listened . i change the code but it is not worked .
return r.unbind("keyup.autocomplete").bind("keyup.autocomplete", o)
.next(".ui-input-clear").bind("click", function() {
s(r, e(i.target))
}).bind("input.autocomplete",o);

bind("input" ) event, but it is not help . and i can give your my website on line . but you maybe have no chinese . can you help me ?

Comment 68 by Raymond Camden posted on 11/2/2013 at 6:09 PM

I'd have to imagine that there is no reason why Chinese text would be a problem. Suggestion: Build a new HTML file - do NOT use jQuery Mobile. Just add jQuery and a keyup listener and use console.log to note the input. Then test your Chinese input.

Basically - test in a much simpler environment and see if it works.

Comment 69 by Federico posted on 2/13/2014 at 2:27 AM

Hi all,
I'm developing a phonegap application with jquery mobile.
When I tested the code in Chrome, all works fine. When I try the same in a device, the autocomplete doesn't work. I guess "$("#inputSearch").on("input", ..." isn't trigger in phonegap build version that I am executing in my device, 'cos I put "alert(1)" and never appears when I write some char in the input.

I'm using query-1.11.0.min.js and PhoneGap 3.

Any suggestion to solve this issue?
Thanks!

Comment 70 by Raymond Camden posted on 2/13/2014 at 4:03 AM

No idea. Are you sure the CDN versions are loading? Can you try local copies.

Comment 71 by Federico posted on 2/13/2014 at 4:15 AM

I load the js locally, I don't use CDN in the project.
I will try replacing the "input" trigger to "keyup". If someone has the same problem, please let me know!

Comment 72 by andy matthews posted on 3/7/2014 at 10:39 AM

LOL. I decided to check out this blog post after answering some questions in my GH repo. Thanks for being tech support for "Andy Matthews code".

:D

Comment 73 by Raymond Camden posted on 3/7/2014 at 5:17 PM

Believe it or not - I had to use this code yesterday.

Comment 74 by Diego posted on 3/14/2014 at 1:07 PM

That's not working on my iPod. I can't pick up an element from my list...

I will work to find out what is wrong.

Comment 75 by Diego posted on 3/14/2014 at 1:44 PM

Use:
$(document).on("touchstart", ... [working on ios and android]

Instead of:
$(document).on("click", ... [working on android and computer explorer]

Comment 76 by falkdav posted on 3/26/2014 at 6:35 PM

Hi Mr. Camden, I have an application That should work online and *offline*, I have some text inputs and JQuery UI Autocomplete plugin:

In the online version, using php I check my external database and I "print" the results in the appropriate place in the <script> </ script>

In the offline version, check my internal database (cordova), and I "print" the results in the appropriate place in the <script> </ script>

The problem is that in the online version looks better than the offline, why?
The suggestions are fixed if I do scroll...

At one input, the total number of suggestions are about 700 ...

What do you recommend for me? and how I could adapt your code to make local queries in databases?

Thanks you!
best regards.

Comment 77 by Raymond Camden posted on 3/26/2014 at 6:58 PM

You got me. In both case an async call is returning results that are displayed - so maybe check for typos. Do you have an online version we can test? Remember that "internal db" is just WebSQL, which works in Chrome, so you can build a version for us to play with online.

Comment 78 by Raymond Camden posted on 3/29/2014 at 5:24 PM

"Uncaught ReferenceError: $ is not defined."
This means you are trying to use jQuery before it is loaded.

Comment 79 by Raymond Camden posted on 4/1/2014 at 10:23 PM

I'm sorry, I don't quite understand what you are asking. If you are still getting an error about $, maybe ensure you didn't use a bad url for jQuery. If you have your code online where we can see, I'll take a quick look.

Comment 80 by Sau posted on 5/29/2014 at 2:59 PM

I am not able to completely understand your code. When we enter the text then what is happening.

Comment 81 by Raymond Camden posted on 5/29/2014 at 3:28 PM

When text is entered, the text is sent to a service (that you build) that returns matched data. So for example, if you had a beer service and the user entered "sa", it could return "Sam Adams Lager" and "Sam Adams Etc". We then display those results below the input field so that the user can select one.

Comment 82 by Sau posted on 5/29/2014 at 3:32 PM

But when I am entering any text, whole data list is displayed.

Comment 83 by Raymond Camden posted on 5/29/2014 at 3:51 PM

Your server needs to look at the input, and return the right data. How that is done depends on your server-side tech and your data. So for example, given an input of "s", I could write SQL to do something like

select name from beers where name like '%#input#'

where input is the value passed to the server.

Comment 84 by denny posted on 5/29/2014 at 9:46 PM

Hello sir, when i using this code to my xampp localhost, it's not working...plzz help

Comment 85 by Raymond Camden posted on 5/29/2014 at 9:47 PM

If you copied my code *exactly*, then you would need ColdFusion. Do you have ColdFusion installed?

Comment 86 by denny posted on 5/29/2014 at 9:51 PM

no sir...
but i want to use it for different api which is a json format file and i want to retrieve name from
name from that file & search according to name ...

Comment 87 by denny posted on 5/29/2014 at 9:52 PM

** retrieve name from that file..

Comment 88 by Raymond Camden posted on 5/29/2014 at 9:56 PM

My code expects something on the server that will respond with the data. My assumption is that you know how to do this already. My blog post was focused on the client-side aspect of this. If you do not know how to do the server-side stuff, then this blog probably won't help you much.

Comment 89 by denny posted on 5/29/2014 at 10:02 PM

http://meerkat.buzz4healtht...
it's my api...
i have replaced "service.cfc?method=getSuggestions" with "http://meerkat.buzz4healtht...".... is it required any code at server side other than this api has ..??

Comment 90 by Raymond Camden posted on 5/29/2014 at 11:02 PM

A json file is not an API. A json file is just static data. You need a dynamic web server on the back end.

Comment 91 by denny posted on 5/29/2014 at 11:24 PM

ok sir...
thank u so much for your guidance ....

Comment 92 by John posted on 9/1/2015 at 7:31 AM

How to get selected item from above listview

Comment 93 (In reply to #92) by Raymond Camden posted on 9/1/2015 at 11:26 AM

If clicking the item loads a new page, you would use regular anchor links. If not, use a touchend handler on the items.

Comment 94 (In reply to #57) by aarthi posted on 9/27/2017 at 6:45 AM

Even I would like to store an array in place of CF. I am confused with this line if (Cities[i].substring(0,text_length) == text) { , what is stored in Cities array. pl help