marhyno
marhyno

Reputation: 699

Autocomplete on dynamic element

I have struggled on this every single time, aaand again today. I am appending new text element and I want to bind autocomplete to it.

This code is in function with previous onClick

$('#highlights').before("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>");

This autocomplete is on the end of the webpage

<script type="text/javascript">
$("#check_name").autocomplete({
      source: "src/check_name.php",
      minLength: 1
    });
</script>

PHP file is working good when I access it via URL.

Upvotes: 0

Views: 706

Answers (2)

TechVision
TechVision

Reputation: 269

Try this way to handle the dynamic control,

var $addedInput=$("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>");
$('#highlights').before($addedInput);
$addedInput.autocomplete({
  source: "src/check_name.php",
  minLength: 1
});

Upvotes: 1

gaetanoM
gaetanoM

Reputation: 42054

Because .before(): insert content, specified by the parameter, before each element in the set of matched elements.

you can use .prev():

The snippet:

var availableTags = [
      "ActionScript",
      "AppleScript",
      "Asp",
      "BASIC",
      "C",
      "C++",
      "Clojure",
      "COBOL",
      "ColdFusion",
      "Erlang",
      "Fortran",
      "Groovy",
      "Haskell",
      "Java",
      "JavaScript",
      "Lisp",
      "Perl",
      "PHP",
      "Python",
      "Ruby",
      "Scala",
      "Scheme"
  ];


  $('#highlights').before("<input type='text' id='check_name' name='name' placeholder='Name of OPM' required class='ui-autocomplete-input'>")
        .prev("#check_name")  // get the newly prev added ele
        .autocomplete({
            source: availableTags,
            minLength: 1
        });
<link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>


<div id="highlights"></div>

Upvotes: 1

Related Questions