Ivan
Ivan

Reputation: 433

Target current dynamic element of each add

How to target the current id-result element for each row added ?

here is now i add the new row

function addFilterRow() {
  html = '<tr id="filter-row">';
  html += '  <td class="text-left">';
  html += '  <select id="company" name="company[]" class="form-control">';
  html += '  {% for company in damask_company %}';
  html += '  <option name="{{ company.filter_group_id }}" value="{{ company.filter_group_id }}">{{ company.name }}</option>';
  html += '  {% endfor %}';
  html += '  </select>';
  html += '</td>';
  html += '<td class="text-left" id="result"></td>';
  html += '</tr>';
  $('tbody').append(html);
}

here is how i try to append it

$(document).on('change', 'select#company', function(e) {
    e.preventDefault();
    var div = $('td#result', this);
    var id = $(this).val();
    var url = "index.php?route=catalog/product/getCat&user_token={{ user_token }}&filter_group_id=" + id;
    $.ajax({
      type: "GET",
      url: url,
      success: function(data) {
        $(data).appendTo(div);
      }
    });
});

Upvotes: 1

Views: 64

Answers (2)

Abdul Rehman Sheikh
Abdul Rehman Sheikh

Reputation: 939

You have to reset the old id="result" before appending the new id="result" by doing this

$.ajax({
      type: "GET",
      url: url,
      success: function(data) {
        $("#result").attr("id", ""); 
        $(data).appendTo(div);
      }
    });

This will remove the attribute ID result to "" empty and then your new id of result will start working. Otherwise it will select the first id of result always.

Upvotes: 0

Rory McCrossan
Rory McCrossan

Reputation: 337627

To achieve this you can use common classes on the elements and DOM traversal to find the content related to the select which raised the change event. This has the added benefit of avoid the id conflict you're creating, as id have to be unique within the DOM.

Firstly amend all the id attributes to classes:

function addFilterRow() {
  html = '<tr class="filter-row">';
  html += '  <td class="text-left">';
  html += '    <select name="company[]" class="company form-control">';
  html += '      {% for company in damask_company %}';
  html += '        <option name="{{ company.filter_group_id }}" value="{{ company.filter_group_id }}">{{ company.name }}</option>';
  html += '      {% endfor %}';
  html += '    </select>';
  html += '  </td>';
  html += '  <td class="text-left result"></td>';
  html += '</tr>';
  $('tbody').append(html);
}

Now you can amend your event handler to retrieve the sibling td:

$(document).on('change', 'select.company', function(e) {
    e.preventDefault();
    var $result = $(this).closest('tr').find('td.result');

    $.ajax({
      type: "GET",
      url: "index.php?route=catalog/product/getCat&user_token={{ user_token }}&filter_group_id=" + $(this).val(),
      success: function(data) {
        $result.append(data);
      }
    });
});

Upvotes: 1

Related Questions