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

时间:2015-09-23 10:14:44

标签: javascript jquery input 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:对不起我的英文......

祝你好运

我的新代码,但是,第一个输入而不是其他输入:

   <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>

为了明确解决这个问题,最后一个想法是什么?

此致

3 个答案:

答案 0 :(得分:0)

您可以为所有输入创建容器(表单,div,等等)并使用event delegation。这将允许您不为每个输入创建事件侦听器。

您的示例代码将是:

<!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>

答案 1 :(得分:0)

在您调用DOM准备好的那一刻,新元素不是DOM的一部分,并且不会是您在$中创建的数组的一部分(&#39;输入[name =&#34;占用[]&# 34;]&#39);

您应该通过重新启动用于将自动完成符添加到元素的函数,将元素添加到数组中。

我删除了这部分,因为它变得非常恐怖。

在您的身体中,您只需要一个包含输入的元素 ID =&#34; occupationsContainer&#34; 和一个按钮 ID =&#34; addNewButton&#34;

那应该做你想做的事;)

最终解决方案:

同样从occupationsContainer元素中删除该按钮,并将其添加到这些括号之外,这将确保元素始终位于输入之下。

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();
});

答案 2 :(得分:0)

解决方案:

<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>

非常感谢你的帮助。