Getting jQueryUi Autocomplete to work with jQueryMobile

Now that JQuery Mobile has matured quite a bit and is getting close to it’s 1.0 release, I decided to take another stab at getting this to work properly. I’ve had good success so I’d like to share the solution here.

Here are the versions I am now currently working with (as of 01-Feb-2012):

jQuery Mobile 1.0.1
jQuery 1.6.4
jQuery UI 1.8.12

The order in which the scripts are referenced is critical. It needs to be jQuery, jQuery UI, jQuery Mobile, then your custom script file last. My page head looks like this:

<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, minimum-scale=1, maximum-scale=1" />
   <title>My jQM App</title>
   <link rel="stylesheet" href="http://ajax.aspnetcdn.com/ajax/jquery.mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
   <script src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.6.4.min.js" type="text/javascript"></script>
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.12/jquery-ui.min.js" type="text/javascript"></script>
   <script src="http://ajax.aspnetcdn.com/ajax/jquery.mobile/1.0.1/jquery.mobile-1.0.1.min.js" type="text/javascript"></script>
   <script src="/Scripts/script.js" type="text/javascript"></script>
   <link rel="stylesheet" href="http://stackoverflow.com/Content/style.css" />
</head> 

All of the autocomplete code should be in a separate .js file and should be the last file linked to. In this sample, mine is script.js.

Next, make sure that all of your page div’s (data-role=”page”) also have an id set. For example, on my search page I have

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

Now that all the page div have id’s you can bind to the jQuery Mobile pagecreate event for that div. In a standard jQuery page you would have something like this for the autocomplete:

$('#search').autocomplete({
    source: '/Autocomplete/SearchAutoComplete',
    minLength: 3,
    select: function (event, ui) { }
});

To do the equivalent but have it hooked up to the specific page div looks like this:

$('#searchPage').live('pageinit', function (event) {
    $('#search').autocomplete({
        source: '/Autocomplete/SearchAutoComplete',
        minLength: 3,
        select: function (event, ui) { }
    });
});

This has been working well for me so far. I’ve been able to strip out most of data-ajax=”false” attributes I had in place as a workaround. This, in turn, has resulted in better application performance. I have by no means done an exhaustive compatibility test between jQuery UI and jQuery Mobile so your mileage may vary. Please leave a comment here if you run into any problems with this method. Good luck.

Leave a Comment