Jquery UI autocomplete JS input

Asked

Viewed 4,025 times

2

Hello I have a problem here when I create an input dynamically and it should work the Widgets autocomplete jquery ui. I saw 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 instantiate the plugin again, using

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

and then

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

right after javascript appendchild. Didn’t work and caused error.

I tried too

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

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

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 am doing so(I use javascript, but there is also another option in jquery 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 created input to this plugin?

2 answers

1

I created an example based on Autocomplete. I modified the script to insert dynamically and set the autocomplete after 2,5 seconds after charging 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>

0

Try, on the last line

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

wear like this:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.