Autocomplete in dynamic input

Asked

Viewed 761 times

1

Good morning, everyone. I’m trying to implement autocomplete in dynamic input but it doesn’t work. Already test calling class or id and nothing.

Follow the code so they can shed some light on where I’m going wrong. Jquery function that adds row to a table dynamically. is the autocomplete function in the descri field (product description)

        $(document).ready(function(){

                //Atribui o evento click a classe .btn-insert-field
                $('.btn-insert-field').click(function(e){
                    //Remove ação padrão do link para não atualiza a página
                    e.preventDefault();

                    //Define o elemento onde será inserido os campos
                    var target  = $("#target");
                    //total de linhas criadas dinamicamente
                    //Será utilizado com indices pra serem removidos mais facilmente
                    var total = $("#target tr").length;
                    //Cria estrutura que será inserida
                    var html   = '<tr class="row-field-'+total+'">';
                            html   += '<td><input type="number" id="qtt" name="qtt[]" /></td>';
                            html   += '<td><input type="text" class="descri" id="descri" name="descri[]" style="text-transform:uppercase"  /></td>';
                            html   += '<td><a href="#" class="btn btn-danger btn-sm  btn-delete-row" data-id="'+total+'">X</a></td>';
                        html   += '<tr>';

                    //Adiciona no final do elemento que foi selecionado anteriormente
                    target.append(html);
                });

                //Atribui a classe .btn-delete-row o evento click
                //É usado on porque o elemento será criado dinamicamente
                $(document).on('click', '.btn-delete-row', function(e){
                    //Remove ação padrão do link para não atualiza a página
                    e.preventDefault();
                    //pega o valor do data-id
                    var id  = $(this).data('id');
                    //Remove a linha
                    $('.row-field-'+id).detach();

                });

                $(document).on('DOMNodeInserted','.descri', function(){
                    $(this).autocomplete({
                        source:'pesquisa_produto.php'
                    });
                });



            });

Inside my html I show in a div ->

                                        <div class="off-3 col-6">
                                                    <table class="actions">
                                                        <thead>
                                                            <tr>
                                                                <th>Quantidade</th>
                                                                <th>Descrição</th>
                                                                <th width="5"><a href="#" class="btn btn-primary btn-insert-field">Adicionar</a></th>
                                                            </tr>
                                                        </thead>
                                                        <tbody id="target"> <!-- aqui aparece a linha da tabela com 2 campos input criados automaticamentes -->

                                                        </tbody>
                                                    </table>
                                            </div>

When I call autocomplete function outside of dynamic input works perfectly.

1 answer

0


Change DOMNodeInserted for focus. When the field, whether dynamically created or not, receives focus, it will gain autocomplete:

$(document).on('focus','.descri', function(){
   // este if verifica se o campo já tem autocomplete
   if( !$(this).hasClass("ui-autocomplete-input") ){
      $(this).autocomplete({
         source:'pesquisa_produto.php'
      });
   }
});

Take an example:

$(function(){
   var availableTags = [
   "ActionScript",
   "AppleScript",
   "Asp",
   "BASIC",
   "C",
   "C++",
   "Clojure",
   "COBOL",
   "ColdFusion",
   "Erlang",
   "Fortran",
   "Groovy",
   "Haskell",
   "Java",
   "JavaScript",
   "Lisp",
   "Perl",
   "PHP",
   "Python",
   "Ruby",
   "Scala",
   "Scheme"
   ];
   
   $(document).on('focus','.descri', function(){
      // este if verifica se o campo já tem autocomplete
      if( !$(this).hasClass("ui-autocomplete-input") ){
         $(this).autocomplete({
            source: availableTags
       });
      }
   });
   
   $("#addicionar").on("click", function(){
      
      $("#box").append('<input class="descri">');
      
   });
   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>

<div id="box">Digite "basic": <input class="descri"></div>
<button id="addicionar">Adicionar input</button>

  • Just as suggested it didn’t work either. I am using the version https://ajax.googleapis.com/ajax/libs/jquery/jqueryui/1.12.1/jquery-ui.min.js and http://code.jquery.com/ui/1.10.3/jquery-ui.js and https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js

  • Strange. I added a functional example in the answer. See that it works normal.

  • Here with me it doesn’t work... why will it be? And this linked correctly.

  • Works in fields that have not been dynamically added?

  • I’m testing here... stopped working too! in the function I call the page search_product.php that looks like this: <?php include_once 'connection.php'; $descri = filter_input(INPUT_GET,'term', FILTER_SANITIZE_STRING); $sql = "SELECT * FROM PRODUCTS WHERE descric LIKE '%". $descri." %' ORDER BY descric ASC LIMIT 5"; $Pdo = Connection::getInstance(); $result = $Pdo->prepare($sql); $result ->execute(); while($Row = $result->fetch(PDO::FETCH_ASSOC)){ $data[] = $Row['descric']; } echo jsonencode_encode($data); ;?>

  • You see this IF I put: if( !$(this).hasClass("ui-autocomplete-input") ){? Makes a else on it and put: console.log("já tem");. Then you will click on the inputs more than 1 time and see if the message appears on the console. If it appears, the code is working correctly and the problem is in the return of PHP.

  • Qdo i Pure... eye on the console does not even enter if... is giving error in line $(Document). on('Focus','. descri', Function(){

  • Which is even stranger. You use other events and no mistake, only the one that is giving? Mt strange.

  • It’s back to normal input but dynamically created input is giving error when I call $(this). autocomplete({ .....

  • Solved... I created a new file . php copied the data from the old paste and started working again... now don’t ask me pq rs.. Vlw the force Sam.

Show 5 more comments

Browser other questions tagged

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