1

I have a table inside a form, where I can add more rows. when I change a value inside a cell, it should run a ajax function. this is working fine on the first row (loaded on page load), but when I add more rows, the function will not affect on the others.

what can I do to to use $("form :input").change('input', urenForm); also on the new rows?

This is not the original script but the main part is in it to show my problem (original is too much to post)

$(document).ready(function() {
  var counter = 0;

  $("#addrow").on("click", function() {
    var newRow = $("<tr>");
    var cols = "";

    cols += '<td><input type="text" class="form-control" name="name' + counter + '"/></td>';
    cols += '<td><input type="text" class="form-control" name="mail' + counter + '"/></td>';
    cols += '<td><input type="text" class="form-control" name="phone' + counter + '"/></td>';

    cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger "  value="Delete"></td>';
    newRow.append(cols);
    $("table.order-list").append(newRow);
    counter++;
  });



  $("table.order-list").on("click", ".ibtnDel", function(event) {
    $(this).closest("tr").remove();
    counter -= 1
  });


});

(function($) {
  function urenForm() {
    event.preventDefault();

    var target = event.target,
      parent = null;

    for (; target && target !== document; target = target.parentNode) {
      if (target.matches('tr')) parent = target;
    }

    var childnodes = parent.querySelectorAll('input, select'),
      data = new FormData();

    for (var i = 0; i < childnodes.length; i++) {
      var child = childnodes[i];
      data.append(child.name, child.value);
    }

    $.ajax({
      url: 'ajax.php',
      dataType: 'json',
      type: 'post',
      data: data,
      processData: false,
      contentType: false,
      success: function(data, textStatus) {
        alert('Changed');
      }
    });
  };
  $("form :input").change('input', urenForm);
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <form>
    <table id="myTable" class=" table order-list">
      <thead>
        <tr>
          <td>Name</td>
          <td>Gmail</td>
          <td>Phone</td>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td class="col-sm-4"><input type="text" name="name" class="form-control" /></td>
          <td class="col-sm-4"><input type="mail" name="mail" class="form-control" /></td>
          <td class="col-sm-3"><input type="text" name="phone" class="form-control" /></td>
          <td class="col-sm-2">
            <a class="deleteRow"></a>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="5" style="text-align: left;"><input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" /></td>
        </tr>
      </tfoot>
    </table>
  </form>
</div>
Barthy
  • 2,624
  • 1
  • 16
  • 37

0 Answers0