How can I add jquery ui autocomplete to a dynamically created element?
Asked Answered
P

3

31

I'm trying to get jQueryUI AutoComplete to trigger on dynamically created form input elements, but it's not working. I've tried using keyup.autocomplete and keydown.autocomplete as bind events in $.live(), but it's binding to the new elements - only those already on the page.

Try out the code here (try typing "ava" in the first input, then click "Add an Input" and type the same in the new input).

JavaScript:

$(function() {
    $("input#addButton").click(function() {
        $("input.searchInput:last").clone(true).appendTo($(this).closest("form"));
        $("input.searchInput:last").val("");

    })

    $("input.searchInput").live("keydown.autocomplete", function() {
        $(this).autocomplete({
            source: [
                "ActionScript",
                "AppleScript",
                "Asp",
                "BASIC",
                "C",
                "C++",
                "Clojure",
                "COBOL",
                "ColdFusion",
                "Erlang",
                "Fortran",
                "Groovy",
                "Haskell",
                "Java",
                "JavaScript",
                "Lisp",
                "Perl",
                "PHP",
                "Python",
                "Ruby",
                "Scala",
                "Scheme"
                ],

            minLength: 2
        });
    })
});

HTML:

<form name="myForm" method="post">
    <input id="addButton" name="addButton" type="button" value="Add an input" />
    <input name="search" value="" class="searchInput" maxlength="20" />
</form>
Parados answered 12/7, 2011 at 20:46 Comment(6)
Just out curiosity, have you tried executing the binding each time a control is created for the specific object created? Good starting point for trouble shooting...Gormless
@Dutchie432: yes, I did - jsfiddle.net/6t74T/2 - same result.Parados
@Eric: Your fiddle (jsfiddle.net/6t74T/1) works for me in Chrome. I get autocomplete on the added box as well.Fyrd
@MrChief: You're right... it works in IE8 too. Hmmm Must be an IE9 issue then....Parados
This works in IE8 only when resetting the bind after the new input is created - jsfiddle.net/6t74T/2. The jsfiddle works, but not my actual code...Parados
I think this has something to do with clone() - it doesn't seem to be copying the handlers - even when specifying withDataAndEvents AND deepWithDataAndEvents.Parados
L
53

Function .live() is deprecated now.

Looks like code like this works:

var options = {
    source: ["ActionScript", "AppleScript"],
    minLength: 2
};
var selector = 'input.searchInput';
$(document).on('keydown.autocomplete', selector, function() {
    $(this).autocomplete(options);
});
Lubricious answered 4/8, 2014 at 8:11 Comment(5)
changing accepted answer since this is compatible with new versions.Parados
Thank you for this! Just helped me with a nested form fields issue in Rails 3.2 trying to get autocomplete working!Hafnium
Hello @Andrei, can you take a look at #33411324 too pls. ThanksNickolenicks
Almost worked for me, I had to change $(this).autocomplete(options); to $(this).autocomplete({source : options}); though.Counteraccusation
Lifesaver! Works like a charm.Aventurine
P
11

This works:

$(function() {
  var options = {
    source: [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
    ],
    minLength: 2
  };

  $("input.searchInput").live("keydown.autocomplete", function() {
    $(this).autocomplete(options);
  });

  var addInput = function() {
    var inputHTML = " <input name='search' value='' class='searchInput' maxlength='20' />";
    $(inputHTML).appendTo("form#myForm");
    $("input.searchInput:last").focus();
  };

  if (!$("form#myForm").find("input.searchInput").length) {
    addInput();
  }

  $("input#addButton").click(addInput);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js"></script>
<form id="myForm" name="myForm" method="post">
  <input id="addButton" name="addButton" type="button" value="Add an input" />
</form>
Parados answered 12/7, 2011 at 21:38 Comment(2)
Hello @Eric, can you take a look at #33411324 too pls. ThanksNickolenicks
Can you look at this questions do you have any solution: #38694416Punctilio
R
0

In case somebody still need, this code will trigger autocomplete when new created input get focus:

$('body').on('focus', 'input[name^=\'[new_element]\']', function () {
    $(this).autocomplete({
        source: ["ActionScript", "AppleScript"],
        minLength: 2
    });
});
Ryley answered 11/10, 2022 at 7:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.