0

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?

2 Answers 2

1

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))
Sign up to request clarification or add additional context in comments.

7 Comments

Hello pai: Thanks for the solution. But it still does not autofill second input field.
@Tanvir updated my answer, you can use the .autoc class selector to bind autocomplete
Thanks for the update. Sorry but it does not update <input type="text" class="autoc" name="mynext" id="prid0">.. <input type="text" class="autoc" name="mynext" id="prid N">
Sorry from my side also. Each row there are two input fields. first input field autocomplete works but second input field should auto fill the value which does not work.
@Tanvir Updated my answer.
|
0

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

6 Comments

Thanks toto. It works only for 1st row 1st column. But it should work for 1st row 2nd column. Also it does not work from 2nd row.
Please see this jsfiddle.net/Lj7PC/5. I want this from 2nd row ....nth row
i observed that in your initial HTML code. <div> don´t end with enclose tag </div>
Yes got this. But still problem is not solved, sorry.
if you update el.find('input:eq(1)') using: el.find('input') ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.