I’m trying to use jquery autocomplete on a text field to allow users to select multiple tags as in this example, but I’m getting the error Uncaught TypeError: Cannot read property 'autocomplete' of undefined. Here’s the code causing the problem, mosly copied from the link.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<script type="text/javascript">
var tags = [<?php
foreach($this->tags as $tag){
echo "\"{$tag['name']}\",";
}
?>""];
$( "textarea:[name='tags']" ).autocomplete({
minLength: 0,
source: function( request, response ) {
// delegate back to autocomplete, but extract the last term
alert($.ui);
$.noConflict();
alert($.ui);
response( $.ui.autocomplete.filter(
tags, extractLast( request.term ) ) );
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
// remove the current input
terms.pop();
// add the selected item
terms.push( ui.item.value );
// add placeholder to get the comma-and-space at the end
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
The error is coming from the line response( $.ui.autocomplete.filter( inside the source. For some reason $( "textarea:[name='tags']" ).autocomplete is perfectly fine and defined, but $.ui.autocomplete isn’t.
I have both jQuery and jQuery UI included above this script. What could be causing this?
EDIT:
I’ve noticed that if I put in alert($.ui); outside of the autocomplete function it displays [Object object], but if I put the same alert inside the source attribute of the autocomplete, it is undefined. Doing the same thing with $ shows that $ is defined inside, but $.ui is not. I also have a datepicker on the page, and it’s showing the same thing, $.ui isn’t defined inside the plugin. Why would jQuery UI be undefined inside these plugins?
EDIT 2:
Putting $.noConflict() in the source attribute right above the response function gets it working just long enough for me to type in one tag, then it crashes the autocomplete, though the datepicker still works. I tried putting it in the create function so it would only execute once, but that just disables all other jQuery on the page.
I’m not very experienced with jQuery or Javascript but it almost seems like the jQuery UI plugins are deleting the alias.
I still have no idea what was causing it, but setting up a counter and an if statement so the $.noConflict only executes once solved the problem.