Input created in JS with jQuery autocomplete UI

Hello I'm having a problem here when I create an input dynamically and it should work jQuery UI autocomplete Widgets. I have seen several forums and they show how to make it work, but my problem is that the function that creates the input is in a javascript function. One of the ideas was to re-instantiate the plugin, using

$( ".selector" ).autocomplete( "destroy" );

And then

 $( ".selector" ).autocomplete( "instance" );

Right after javascript appendChild. It did not work and caused error.

I tried also

$(document.body).on('focus', 'input.item_extra' ,function(){
     // código
}

According to some tutorials this should also work, but not with me.

The code I use in the inputs already created is:

$.ajax({
            url: "../_lib/siclop_auto_complete/itens_extras.xml",
            dataType: "xml",
            success: function( xmlResponse ) {
                var dataItemExtra = $( "item_extra", xmlResponse ).map(function() {
                    return {
                        value: $( "item", this ).text()
                    };
                }).get();
                $( ".item_extra" ).autocomplete({ // Produto principal
                    source: dataItemExtra,
                    minLength: 0,
                    select: function( event, ui ) {
                        inclui_item_extra(ui.item.value,this.id);
                        this.value = "";
                        this.focus();
                        return false;
                    }
                });
            }
        });

And to add the element, I'm doing so (I use javascript, but ai has also another option in jquery that I found on the internet.):

                var add_item_extra = document.createElement("input");
            add_item_extra.setAttribute('type', 'text');
            add_item_extra.setAttribute('placeholder', 'Adicionar Item Extra');
            add_item_extra.setAttribute('class', 'input_item_extra');

        //add_item_extra.className = 'item_extra';

            $insert = jQuery(cell3);
            $insert.append(add_item_extra);
            $insert.find('.item_extra').autocomplete();

        //cell3.appendChild(add_item_extra);

This attempt with jquery tbm did not work. How do I then add this input created via javascript to this plugin?

Author: Matheus Delatorrre, 2017-08-03

2 answers

I created an example based on the documentation of Autocomplete. I modified the script to dynamically insert and set the autocomplete after 2.5 seconds after loading the DOM. The code is commented item by item and easy to understand, just adapt it to your code.

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

console.log('Script inicializado, mas não antes do final do ready do DOM.');

$(function() {

  console.log('DOM Ready, começando...');

  // Timeout de 2,5 segundos
  setTimeout(function() {

    console.log('Inserindo elementos dinamicamente no DOM depois de 2,5 segundos');

    // Variável para guardar os elementos html para serem inseridos
    var novosInputs = [];

    // Cria primeiro input
    novosInputs.push($('<input />', {
      class: "autocomplete",
      placeholder: "Campo 01, digite aqui"
    }));

    // Cria segundo input
    novosInputs.push($('<input />', {
      class: "autocomplete",
      placeholder: "Campo 02, digite aqui também"
    }));

    // Div que receberá os inputs
    var wrapper = $('.content-after-ready');

    // Adiciona os inputs ao DOM
    wrapper.html(novosInputs);

    // Procura pelos inputs inseridos
    var getInputs = wrapper.find('.autocomplete');

    // Percorre os inputs e adicionando o autocomplete em cada um
    $.each(getInputs, function(key, element) {
      $(element).autocomplete({
        source: availableTags
      });
    });
  }, 2500); // Aguarda 2,5 segundos para executar este bloco

});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

<div class="ui-widget">
  <label for="tags">Tags: </label>
  <div class="content-after-ready"></div>
</div>
 1
Author: Bruno Rigolon, 2017-08-07 19:59:20

Try, on the last line

$insert.find('.item_extra').autocomplete();

Use like this:

$insert.find('.item_extra').autocomplete(true);
 0
Author: Cássio Giehl da Rosa, 2018-07-17 12:18:22