0

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.

marhyno
  • 677
  • 1
  • 8
  • 20
  • Possible duplicate: [jQuery autocomplete for dynamically created inputs](http://stackoverflow.com/questions/2663573/jquery-autocomplete-for-dynamically-created-inputs) – Hans Wassink Feb 23 '17 at 15:45
  • maybe it is, but I already checked that answer and It didnt help me. That guys has different code there. – marhyno Feb 23 '17 at 15:47

2 Answers2

1

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>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61
1

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
});
TechVision
  • 269
  • 1
  • 11