Tanvir
Tanvir

Reputation: 151

Jquery autocomplete multiple dynamic input array

I have created a dynamic input arrray. It works fine for adding and deleting input fields. It also works fine for populating value in first input field. Problem is after adding multiple input fields, it does not work for autocomplete. The problem might be assiging each dynamic array identically and populate autocomplete accordingly. I have googled many times but did not find similar problem. Here is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

</head>
<body>
    <div class="input_fields_wrap">
        <button class="add_field_button">Add More Fields</button><br>
        <div><input type="text" class="autoc" name="mytext[]" id="choice0"><input type="text" class="autoc" name="mynext[]" id="prid0"></div>
    </div>

<script>
    $(document).ready(function() {
        var max_fields      = 10; //maximum input boxes allowed
        var wrapper         = $(".input_fields_wrap"); //Fields wrapper
        var add_button      = $(".add_field_button"); //Add button ID
        
        var x = 1; //initlal text box count
        var availableAttributes = [
            {"label":"[email protected]","value":"Business Planning & Supply Chain"},
            {"label":"[email protected]","value":"Marketing"},
            {"label":"[email protected]","value":"Sales"},
            {"label":"[email protected]","value":"Technology"}
        ];
        
        
        $(add_button).click(function (e) { //on add input button click
            e.preventDefault();
            if (x < max_fields) { //max input box allowed
                x++; //text box increment
                var el = $('<div><input type="text" name="mytext[]" id="choice' + (x - 1) + '"><input type="text" name="mynext[]" id="prid' + (x - 1) + '"><a href="#" class="remove_field">Remove</a></div>');
                $(wrapper).append(el);

                el.find('input:eq(1)').autocomplete({
                    source: availableAttributes,
                    select: function (event, ui) {
                        event.preventDefault();
                       var parent =  $(this).parent("div");
                        parent.find("input:eq(0)").val(ui.item.label);
                        parent.find("input:eq(1)").val(ui.item.value);
                    }
                });
                //add input box
            }
        });
        
        $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
            e.preventDefault(); $(this).parent('div').remove(); x--;
        })
        
        $("input[name^='mytext']").autocomplete({
            source: availableAttributes,
            select: function( event, ui ) {
                event.preventDefault();
                var parent =  $(this).parent("div");
                parent.find("input:eq(0)").val(ui.item.label);
                parent.find("input:eq(1)").val(ui.item.value);
            }
        }); 
        
    });
</script>

</body>
</html>

Could you please help?

Upvotes: 0

Views: 907

Answers (2)

painotpi
painotpi

Reputation: 6996

There's a problem with your selector when you try to bind the autocomplete for the newly added element,

$(wrapper).find('input[type=text]:last')

This selector does not match the newly added element given the way your DOM is structured, you would be better of adding a new class on the newly added div and then using that to select the inputs to bind the autocomplete as follows,

$(document).ready(function() {
  var max_fields = 10; //maximum input boxes allowed
  var wrapper = $(".input_fields_wrap"); //Fields wrapper
  var add_button = $(".add_field_button"); //Add button ID

  var x = 1; //initlal text box count
  var availableAttributes = [{
      "label": "[email protected]",
      "value": "Business Planning & Supply Chain"
    },
    {
      "label": "[email protected]",
      "value": "Marketing"
    },
    {
      "label": "[email protected]",
      "value": "Sales"
    },
    {
      "label": "[email protected]",
      "value": "Technology"
    }
  ];


  $(add_button).click(function(e) { //on add input button click
    e.preventDefault();
    if (x < max_fields) { //max input box allowed
      x++; //text box increment
      $(wrapper).append('<div class="added"><input type="text" name="mytext[]" id="choice' + (x - 1) + '"><input type="text" name="mynext[]" id="prid' + (x - 1) + '"><a href="#" class="remove_field">Remove</a></div>');
      
      $('.added input').autocomplete({
        source: availableAttributes,
        select: function(event, ui) {
          event.preventDefault();
          $('#choice' + (x - 1)).val(ui.item.label);
          $('#prid' + (x - 1)).val(ui.item.value);
        }
      });
      //add input box
    }
  });

  $(wrapper).on("click", ".remove_field", function(e) { //user click on remove text
    e.preventDefault();
    $(this).parent('div').remove();
    x--;
  })

  $(".autoc:first-child").autocomplete({
    source: availableAttributes,
    select: function(event, ui) {
      event.preventDefault();
      $('#choice' + (x - 1)).val(ui.item.label);
      $('#prid' + (x - 1)).val(ui.item.value);
    }
  });

});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js" integrity="sha256-T0Vest3yCU7pafRw9r+settMBX6JkKN06dqBnpQ8d30=" crossorigin="anonymous"></script>

<div class="input_fields_wrap">
  <button class="add_field_button">Add More Fields</button><br>
  <div>
    <input type="text" class="autoc" name="mytext" id="choice0">
    <input type="text" class="autoc" name="mynext" id="prid0">
  </div>
</div>

EDIT:

You will also need to wrap the x-1 with parenthesis when you add your selector to update values,

$('#choice' + (x - 1))

Upvotes: 1

toto
toto

Reputation: 1188

try it part of your code:

                 $(add_button).click(function (e) { //on add input button click
                    e.preventDefault();
                    if (x < max_fields) { //max input box allowed
                        x++; //text box increment
                        var el = $('<div><input type="text" name="mytext[]" id="choice' + (x - 1) + '"><input type="text" name="mynext[]" id="prid' + (x - 1) + '"><a href="#" class="remove_field">Remove</a></div>');
                        $(wrapper).append(el);

                        el.find('input:eq(1)').autocomplete({
                            source: availableAttributes,
                            select: function (event, ui) {
                                event.preventDefault();
                               var parent =  $(this).parent("div");
                                parent.find("input:eq(0)").val(ui.item.label);
                                parent.find("input:eq(1)").val(ui.item.value);
                            }
                        });
                        //add input box
                    }
                });

Upvotes: 0

Related Questions