M.Gooda
M.Gooda

Reputation: 137

how to loop after specified number of rows in table

I have a <table id="table">.

A user can add rows in this table when clicking <button id="new">.

A user can save by clicking <button id="save">

If a user adds more than 5 rows without saving data, then they should get an alert to save. This alert should be repeated in each 5 new rows.

I've tried this :

$('#new').click(function(){
  var count = $('#table tbody').children('tr').length;
  if (count > 4) {
  var y = confirm("you should to save your data!");
  if (y == true){
    $('#save').click();
  }
  else {

  }
});

Upvotes: 0

Views: 41

Answers (2)

Davide Melfi
Davide Melfi

Reputation: 250

A different elegant way is the following:

$('#new').click(function(){

  var $newRow = $('<tr><td>new</td></tr>').appendTo('table')

  if ($newRow.is('table tr:nth-child(5n)')){
    alert('Alert')
  };

});

Upvotes: 0

smaili
smaili

Reputation: 1235

Instead of using the > operator, you should use the modulo operator.

So change your if to this:

if (count > 0 && count % 5 == 0) {

Upvotes: 1

Related Questions