1

Sorry for asking the question that has been asked so many times before. But I could not find a correct solution that solves my problem. So please consider this as a followup.

I have a button (#addNewElement) that adds an input field and a select dropdown on click. I have attached autocomplete function for the text input field. But the problem is, whenever I change one of the inputs of any of the fields, all of them get changed too. Why are all of them changing together? What am I missing here?

$("#addNewElement").click(function() {
    $('#addElement').append("<div>\n\
        <label class='form-name'>Element name: </label>\n\
        <input type='text' name='element_name[]' id='element_name' class='eName'>\n\
        </div>\n\
        <div>\n\
        <select name='formulation[]' id='formulation'>\n\
        <option value=''>Select Formulation</option>\n\
        </select>\n\
                </div>");
    $(".eName").autocomplete({
        source: 'search.php',
        select: function(event, ui) {
            $(".eName").val(ui.item.value)
        }
    });
});

Also, I have an on change function attached to these input fields. This on change function works fine with the static field, but when comes to the dynamically added fields, it doesn't work. (I have included this section because I think they are related to the same problem).

$('.eName').change(function() {
            if ($(this).val() != '') {
                var action = $(this).attr("id");
                var query = $(this).val();
                var result = '';
                if (action == "element_name") {
                    result = 'formulation';
                } else {
                    result = 'strength';
                }
                $.ajax({
                    url: "fetch.php",
                    method: "POST",
                    data: {
                        action: action,
                        query: query
                    },
                    success: function(data) {
                        $('#' + result).html(data);
                    }
                })
            }

Are these two problems connected? How should I overcome these? Thanks in advance for your suggestions.

Ashonko
  • 339
  • 4
  • 29
  • Could you post a working fiddle if possible. – Sree Nath Nov 20 '17 at 12:52
  • Post your html and make it as snippet or fiddle – Sylwek Nov 20 '17 at 12:53
  • 1
    For the first problem, the class is the guilty one. You tell literally to update all elements that have the class when one is changed, try with `$(this).val(ui.item.value)`. For your second problem, refer to [this link](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Kaddath Nov 20 '17 at 12:53
  • Wow! @Kaddath! Thanks a lot. Solved the first problem. On the way to solve the second one. – Ashonko Nov 20 '17 at 12:57

1 Answers1

0

When you append your element, you're creating elements with the same id attribute. This can cause various problems. It should also be unique.

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

Consider the following:

$("#addNewElement").click(function(e) {
  var newDiv = $("<div>").appendTo("#addElement");
  $("<label>", {
    class: "form-name"
  }).html("Element Name: ").appendTo(newDiv);
  var newInp = $("<input>", {
    type: "text",
    name: "element_name[]",
    id: "element_name-" + ($("[id|='element_name']").length + 1)
  }).appendTo(newDiv);
  var newDiv2 = $("<div>").appendTo("#addElement");
  var newSel = $("<select>", {
    name: "formulation[]",
    id: "formulation-" + ($("[id|='formulation']").length + 1)
  }).appendTo(newDiv2);
  $("<option>", {
    value: ""
  }).html("Select Formulation").appendTo("newSel");
  newInp.autocomplete({
    source: 'search.php',
    select: function(event, ui) {
      newInp.val(ui.item.value);
    }
  });
});

This simply ensures that you have a unique ID for each element. You ca do this in your HTML string too. I find that jQuery objects are just a bit cleaner looking and easier to manipulate when creating them.

Also, since the element was created and stored to a variable, you can target that specific element when creating and updating the autocomplete.

Twisty
  • 23,484
  • 1
  • 22
  • 40