Input created in JS with autocomplete of JQuery UI

2

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

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

and then

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

shortly after the appendChild of javascript. It did not work and it caused an error.

I've tried it too

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

According to some tutorials, this should 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 there's also another jquery option 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 javascript input to this plugin?

    
asked by anonymous 03.08.2017 / 20:33

2 answers

0

I created an example based on the Autocomplete documentation. I modified the script to dynamically insert and set autocomplete after 2.5 seconds after loading 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><scriptsrc="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>
    
07.08.2017 / 21:59
0

Try, on the last line

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

use like this:

$insert.find('.item_extra').autocomplete(true);
    
17.07.2018 / 14:18