简体   繁体   English

动态创建的jQuery自动完成输入文本

[英]Jquery autocomplete input text created dynamically

I'm trying to do a code in order that users can add an unlimited numbers of occupations via a "+" button which create input text occupation[]. 我正在尝试编写代码,以便用户可以通过“ +”按钮创建输入文本职业[]来添加无限数量的职业。 But when the new input text is created, he cannot be autocomplete like the others natives input (not created dynamically). 但是,在创建新输入文本时,他不能像其他本机输入(不是动态创建)一样自动完成。

So how to add correctly new input text for permit autocompletion of all the input ? 那么,如何正确添加新的输入文本以允许所有输入自动完成?

Here is my Jquery code for autocomplete: 这是我的自动完成的Jquery代码:

    $('input[name="occupation[]"]').on("keyup", function(){
    var occup = $(this).val();
    var currentElement = $(this);       
    if(occup != ""){ 
        $.ajax({
            type: "GET",
            url: "page_geneoccup.php",
            data: {"occup":occup},
            dataType: 'json',
            success:function(responseData){
                var liste_occup=responseData; 
                $(currentElement).autocomplete({
                    source: liste_occup
                }); 
                return;
            },
            error:function(XMLHttpRequest, textStatus, errorThrow){
                console.log("Error: " + XMLHttpRequest.status + errorThrow );
                return;
            }
        });
    }
});

PS: Sorry for my english... PS:对不起,我的英语...

Best regards 最好的祝福


My new code but, functioning for the first input and not for the others: 我的新代码,但是对第一个输入起作用,而不对其他输入起作用:

   <html lang="fr">
<head>
<meta charset="utf-8" />         
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>


    var oAutoCompleteElements = {
    addInputEvents:function(newInputs){
        var r_newInputs = $(newInputs);
        $(newInputs).each(function(i, oInput){
            $(oInput).off();
            $(oInput).on('keyup',function(){
                var occup = $(oInput).val();
                if(occup){
                $.ajax({
                type: "GET",
                url: "page_geneoccup.php",
                data: {"occup":occup},
                dataType: 'json',
                success:function(responseData){
                    var liste_occup=responseData; 
                    $(oInput).autocomplete({
                        source: liste_occup
                    }); 
                    return;
                },
                error:function(XMLHttpRequest, textStatus, errorThrow){
                    console.log("Error: " + XMLHttpRequest.status + errorThrow );
                    return;
                }
            });
                }
            });
        });
    },
    addButtonEvents:function(){
        $('#addNewInput').on('click',function(){
            oAutoCompleteElements.addNewInput();
        });
    },
    addNewInput:function(){
        newInput ='<input type="text" name="occupation[]"/>';
        $('#occupationsContainer').append(newInput);
          oAutoCompleteElements.addInputEvents($('input[name="occupation[]"]:last'));
    },
    init:function(){
       this.addButtonEvents();
       this.addInputEvents($('input[name="occupation[]"]'));
    }
};

$(function(){
    oAutoCompleteElements.init();
});


var counter = 1;
function addInput()
{
          var target        = document.getElementById('occupationsContainer');
          var newdiv        = document.createElement('div');
          var newdivname    = 'Div' + counter;
          newdiv.setAttribute('id',newdivname);
          content = newdiv.innerHTML;
          content +='<input name="occupation[]">';
          content +='<a id="AccountDelete" href="#" onclick="removeInput(\'' + newdivname + '\');">[Supprimer cet enfant]</a><br><br><hr><br><br>';
          newdiv.innerHTML = content;
          target.appendChild(newdiv);
          counter++;
}

function removeInput(idInput)
{
    var elmt = document.getElementById(idInput);
    elmt.parentNode.removeChild(elmt);
}   
    </script>

    </head>
    <body>



<div  id="occupationsContainer">
<input name="occupation[]">
<input type="button"  id="addNewButton" value="add" onclick="addInput();">
</div>

    </body>
    </html>

A last idea in order to definitely solve this problem ? 为了绝对解决这个问题的最后一个想法?

Regards 问候

You could make a container (a form, div, whatever) for all the inputs and use event delegation . 您可以为所有输入创建一个容器(窗体,div,等等),并使用事件委托 This would allow you to not create event listeners for each of the inputs. 这将使您不必为每个输入创建事件侦听器。

Your example code would then be: 您的示例代码将为:

<!DOCTYPE html>
<html lang="fr">

<head>
  <meta charset="utf-8" />
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" />
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
  <script>
    var addNewInput = function() {
      $('#occupationsContainer').append('<input name="occupation[]" />');
    }

    /* delete last input from occupationsContainer, 
       but make sure it's not the first one */
    var deleteInput = function() {
      $('#occupationsContainer>input').not(':first').remove(':last');
    }

    /* this listens for keyup event on any input in the element
       with id occcupationsContainer */
    $('#occupationsContainer').on("keyup", "input", function() {
      var occup = $(this).val();
      var currentElement = $(this);
      if (occup != "") {
        $.ajax({
          type: "GET",
          url: "page_geneoccup.php",
          data: {
            "occup": occup
          },
          dataType: 'json',
          success: function(responseData) {
            var liste_occup = responseData;
            $(currentElement).autocomplete({
              source: liste_occup
            });
            return;
          },
          error: function(XMLHttpRequest, textStatus, errorThrow) {
            console.log("Error: " + XMLHttpRequest.status + errorThrow);
            return;
          }
        });
      }
    });
  </script>
</head>

<body>
  <button id="addBtn" onclick="addNewInput()">Add</button>
  <button id="removeBtn" onclick="deleteInput()">Remove</button>
  <div id="occupationsContainer">
    <input name="occupation[]" />
  </div>

</body>

</html>

the new element is not part of the DOM at the moment you call DOM ready, and will not be part of the array you create in $('input[name="occupation[]"]'); 在您调用DOM就绪时,新元素不属于DOM,也不属于您在$('input [name =“ occupation []”]')中创建的数组的一部分;

You should add the element to the array, either by reinitiating the function you use to add the autocompleter to your elements. 您应该通过重新启动用于将自动完成程序添加到元素的函数来将元素添加到数组。

I removed this part because it was getting to freaking long. 我删除了这部分,因为它变得越来越长了。

In your body you only need an element containing your inputs with id="occupationsContainer" and a button with id="addNewButton" 在您的身体上,您只需要一个包含id =“ occupationsContainer”输入的元素和一个id =“ addNewButton”按钮的元素

and that should do what you want ;) 那应该做你想要的;)

final solution: 最终解决方案:

Also remove the button from the occupationsContainer element,And add it outside of those brackets, this will make sure that element is always beneath the inputs. 还要从职业容器元素中删除按钮,并将其添加到这些括号之外,以确保该元素始终位于输入下方。


var oAutoCompleteElements = {
    counter:1,
    addInputEvents:function(newInputs){
       var r_newInputs = $(newInputs);
       $(newInputs).each(function(i, oInput){
           $(oInput).off();
           $(oInput).on('keyup',function(){
              var occup = $(oInput).val();
              if(occup){
                  console.log('a call to your autocompleter list');
              }
          });

         //add events to the new deleteButton
         var deleteInput = $(oInput).parent().find('.deleteInput');
         $(deleteInput).each(function(i, oDelete){
              $(oDelete).on('click',function(){
                  oAutoCompleteElements.removeInput($(oInput).parent());
              });
          });
       });
    },
    //add events to the add button,
    addButtonEvents:function(){
        $('#addNewInput').on('click',function(){
            oAutoCompleteElements.addNewInput();
        });
    },
    //add a new input
    addNewInput:function(){
        newInput ='<div id="Div' + oAutoCompleteElements.counter + '"><input    type="text" name="occupation[]"/><a class="deleteInput">[Supprimer cet enfant]</a></div>';
         oAutoCompleteElements.counter ++ ;
         $('#occupationsContainer').append(newInput);

         oAutoCompleteElements.addInputEvents($('input[name="occupation[]"]:last'));
    },
    //remove an input
    removeInput:function(oInput_container){
       $(oInput_container).remove();
       oAutoCompleteElements.counter --;
    },
    init:function(){
       this.addButtonEvents();
       this.addInputEvents($('input[name="occupation[]"]'));
    }
};

$(function(){
    oAutoCompleteElements.init();
});

The solution: 解决方案:

<html lang="fr">
<head>
<meta charset="utf-8" />         
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>


    var oAutoCompleteElements = {
    addInputEvents:function(newInputs){
        var r_newInputs = $(newInputs);
        $(newInputs).each(function(i, oInput){
            $(oInput).off();
            $(oInput).on('keyup',function(){
                var occup = $(oInput).val();
                if(occup){
                $.ajax({
                type: "GET",
                url: "page_geneoccup.php",
                data: {"occup":occup},
                dataType: 'json',
                success:function(responseData){
                    var liste_occup=responseData; 
                    $(oInput).autocomplete({
                        source: liste_occup
                    }); 
                    return;
                },
                error:function(XMLHttpRequest, textStatus, errorThrow){
                    console.log("Error: " + XMLHttpRequest.status + errorThrow );
                    return;
                }
            });
                }
            });
        });
    },
    addButtonEvents:function(){
        $('#addNewInput').on('click',function(){
            oAutoCompleteElements.addNewInput();
        });
    },
    addNewInput:function(){
        newInput ='<input type="text" name="occupation[]"/>';
        $('#occupationsContainer').append(newInput);
          oAutoCompleteElements.addInputEvents($('input[name="occupation[]"]:last'));
    },
    init:function(){
       this.addButtonEvents();
       this.addInputEvents($('input[name="occupation[]"]'));
    }
};

$(function(){
    oAutoCompleteElements.init();
});



    </script>

    </head>
    <body>



<div  id="occupationsContainer">
<input name="occupation[]">
<input type="button"  id="addNewInput" value="add">
</div>

    </body>
    </html>

Thank you a lot for your help. 非常感谢您的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM