jQuery UI autocomplete: Uncaught TypeError: Cannot read property ‘element’ of undefined
I got that exception when I loaded some options through JSON (with ASP.NET MVC). It took a lot of digging before I finally found the cause. And it’s not what I expected:
I’ve made a custom menu plugin in the jQuery namespace. And it seems like autocomplete tries to use the ‘menu’ function ($jQuery.menu) too, which failed utterly. I removed my plugin and everything worked smoothly.
Here’s how you can use the autocomplete plugin yourself with Ajax (I preload all available options):
In your Razor view:
<script type="text/javascript">
var baseUri = '@Url.Content("~")'; // to get it working in root or a virtual dir
$(function() {
$.getJSON(baseUri + 'myController/myAction', function(data) {
$('myTextbox').autocomplete({ source: data });
});
});
</script>
And in your controller:
public ActionResult Items()
{
var items = _repository.GetYourItems().Select(p => p.Title).ToList(); // only get titles
return Json(items, JsonRequestBehavior.AllowGet); //it's safe to get these items using GET
}