title: Jquery add and remove table rows
body: <p>I have a html table that dynamically adds and removes rows with jQuery. The number of rows is limited by jQuery counter which allows a user to add up to 4 rows. My problem is that when a user creates the 4th row they have reached the limit but when they delete a row the limit still remains in place and they can't add any more rows.</p>
  
  <p><a href="http://jsfiddle.net/nallad1985/sqrrt/" rel="nofollow noreferrer">http://jsfiddle.net/nallad1985/sqrrt/</a></p>
  
  <p><strong>HTML</strong></p>
  
  <pre><code>&lt;table id="myTable" class="order-list"&gt;
  &lt;thead&gt;
      &lt;tr&gt;
          &lt;td&gt;Name&lt;/td&gt;
          &lt;td&gt;Price&lt;/td&gt;
      &lt;/tr&gt;
  &lt;/thead&gt;
  &lt;tbody&gt;
      &lt;tr&gt;
          &lt;td&gt;
              &lt;input type="text" name="name" /&gt;
          &lt;/td&gt;
          &lt;td&gt;
              &lt;input type="text" name="price1" /&gt;
          &lt;/td&gt;
          &lt;td&gt;&lt;a class="deleteRow"&gt;&lt;/a&gt;
          &lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tbody&gt;
  &lt;tfoot&gt;
      &lt;tr&gt;
          &lt;td colspan="5" style="text-align: left;"&gt;
              &lt;input type="button" id="addrow" value="Add Row" /&gt;
          &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
          &lt;td colspan=""&gt;Grand Total: $&lt;span id="grandtotal"&gt;&lt;/span&gt;
  
          &lt;/td&gt;
      &lt;/tr&gt;
  &lt;/tfoot&gt;
  </code></pre>
  
  <p></p>
  
  <p><strong>JQUERY</strong></p>
  
  <pre><code>$(document).ready(function () {
  var counter = 0;
  $("#addrow").on("click", function () {
      var counter = $('#myTable tr').length - 2;
      var newRow = $("&lt;tr&gt;");
      var cols = "";
  
      cols += '&lt;td&gt;&lt;input type="text" name="name' + counter + '"/&gt;&lt;/td&gt;';
      cols += '&lt;td&gt;&lt;input type="text" name="price' + counter + '"/&gt;&lt;/td&gt;';
  
      cols += '&lt;td&gt;&lt;input type="button" id="ibtnDel"  value="Delete"&gt;&lt;/td&gt;';
      newRow.append(cols);
      if (counter == 4) $('#addrow').attr('disabled', true).prop('value', "You've reached the limit");
      $("table.order-list").append(newRow);
      counter++;
  });
  
  $("table.order-list").on("change", 'input[name^="price"]', function (event) {
      calculateRow($(this).closest("tr"));
      calculateGrandTotal();
  });
  
  $("table.order-list").on("click", "#ibtnDel", function (event) {
      $(this).closest("tr").remove();
      calculateGrandTotal();
  });
  
  });
  
  function calculateRow(row) {
  var price = +row.find('input[name^="price"]').val();
  
  }
  
  function calculateGrandTotal() {
  var grandTotal = 0;
  $("table.order-list").find('input[name^="price"]').each(function () {
      grandTotal += +$(this).val();
  });
  $("#grandtotal").text(grandTotal.toFixed(2));
  }
  </code></pre>