0

I am using the autocomplete functionality from jQuery and am having a small problem. I have a div element with some text and a variable number of input boxes that have autocomplete functionality. When a user clicks on the text in the div element, the input boxes are removed. Clicking on the text toggles between showing the input boxes and not showing the input boxes. With each text click a php script is called that returns new html text for the div element.

The autocomplete inputs are created with php code similar to the following:

php code

echo "<id='a' value='Smith' autocomplete='off'>";
echo "<script type=\"text/javascript\">$('a').autocomplete('do_name_lookup.php',{minChars:3,max:999});</script>";
echo "<script type=\"text/javascript\">$('a').result(function(event, data, formatted) {alert(data[0])});</script>";

On a static web page the two script elements would appear in the "$(document).ready" function. Since my page is dynamic, however, the input boxes are created a long time after $(document).ready has fired. Therefore, I have to execute the javascript code just after each of the input boxes is made. This setup works fine the first time the php code above is executed, but the second time the code is executed, the autocomplete functionality goes away.

Can anyone explain to me why this is happening and how to work around it? My suspicion is that I am declaring a variable with the same name multiple times and this is creating a conflict of some type.

nalply
  • 26,770
  • 15
  • 78
  • 101
jay
  • 2,533
  • 3
  • 20
  • 21
  • I have further refined the problem I am having. The problem (autocomplete stops working) occurs when I dynamically remove an element (e.g., a table row that contains an autocomplete input item) from my page. – jay Jan 19 '10 at 16:08
  • How is that php that you reference called? Some ajax method? – Ender Dec 08 '10 at 18:17
  • Update: The problem had to do with having multiple selectors/elements with the same name. I got around this problem by adding a random number to the end of the selector name. This made each selector unique and the autocomplete was happy again. – jay May 07 '13 at 13:40
  • A better solution is given here: http://stackoverflow.com/questions/6670918/how-can-i-add-jquery-ui-autocomplete-to-a-dynamically-created-element combined with http://stackoverflow.com/questions/9693758/how-do-you-bind-jquery-ui-autocomplete-using-on. – jay May 07 '13 at 13:40

1 Answers1

0
<id='a' value='Smith' autocomplete='off'>

This is no valid element, it misses a tag name. Want to amend "input"?

$('a')…

This selects all anchor elements (links) in the page. I guess you wanted the id selector $('#a').

Also, you should really combine the two script elements to one. Not only because there are limits in some browsers. A <script> may contain more than one JavaScript statement, and you just may want to chain the two methods of the same selected element.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375