user7323189
user7323189

Reputation:

Jquery add row dele buttons?

I want to add the insertion button in the following code directory

How can I add a button to the insert section.

$(document).ready(function() {
  $('#row_add_btn').click(AddRows)
  
  var number = 1;
  function AddRows() {
    number++;
    if (number < 21) {
      var AddToRows = '<p><input name="icerik' + number + '"/> <input name="icerik' + number + '" /><input type="button" class="ibtnDel"></p>'

      $('#list_add_rows').append(AddToRows)
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="list_add_rows">
  <p>
    <input type="text" name="icerik1" />
    <input type="text" name="icerik1" />
  </p>
</div>
<a id="row_add_btn">Add</a>

Upvotes: 1

Views: 36

Answers (2)

Will P.
Will P.

Reputation: 8787

If you want the button click to remove the row, this jQuery should do the trick:

$(document).on("click", ".ibtnDel", function () {
    $(this).parent().remove();
});

jQuery on() documentation

Upvotes: 1

Ajay Narain Mathur
Ajay Narain Mathur

Reputation: 5466

If you planning to insert deletion of the the rows then you need to use the code what Will P. suggested above but in addition you will need to handle the maximum number of rows differently.

Increment the number in if condition and decrement on remove row.

Example Snippet:

$(document).ready(function() {
  $('#row_add_btn').click(AddRows);
  $(document).on('click', '.ibtnDel', removeRow);
  var number = 1;

  function AddRows() {
    if (number <= 21) {
      number++;
      var AddToRows = '<p><input name="icerik' + number + '"/> <input name="icerik' + number + '" /><input type="button" class="ibtnDel"></p>'

      $('#list_add_rows').append(AddToRows)
    }
  }

  function removeRow() {
    number--;
    $(this).parent().remove();
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="list_add_rows">
  <p>
    <input type="text" name="icerik1" />
    <input type="text" name="icerik1" />
  </p>
</div>
<a id="row_add_btn">Add</a>

Upvotes: 0

Related Questions