Increase in JavaScript function

1

I'm having trouble incrementing a javascript function.

I have a table with the following structure:

<table id="products-table">
<tbody>
 <tr>
   <th>Produto</th>
   <th>Código</th>
   <th>Quantidade</th>
   <th>Preço</th>
   <th>Ações</th>
 </tr>
 <tr>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>
     <button onclick="RemoveTableRow(this)" type="button">Remover</button>
   </td>
 </tr>
</tbody>
<tfoot>
 <tr>
   <td colspan="5" style="text-align: left;">
     <button onclick="AddTableRow()" type="button">Adicionar Produto</button>
   </td>
 </tr>
</tfoot>
</table>

The RemoveTableRow (this) function has the following commands:

(function($) {
  remove = function(item) {
    var tr = $(item).closest('tr');
    tr.fadeOut(400, function() {
      tr.remove();  
    });
    return false;
  }
})(jQuery);

The AddTableRow () function has the following content:

var inicio = 1;
var maximo = 5;
(function($) {
if (inicio <= maximo) {
  AddTableRow = function() {
    var newRow = $("<tr>");
    var cols = "";
    cols += '<td>&nbsp;</td>';
    cols += '<td>&nbsp;</td>';
    cols += '<td>&nbsp;</td>';
    cols += '<td>&nbsp;</td>';
    cols += '<td>';
    cols += '<button onclick="RemoveTableRow(this)" type="button">Remover</button>';
    cols += '</td>';
    newRow.append(cols);
    $("#products-table").append(newRow);
    return false;
  };
    }
    inicio++;
})(jQuery);

These two functions insert and remove dynamic rows from a table. I need to create a condition so that it is allowed to insert only 5 rows and that when a row is deleted the counter will update itself.

At the beginning of the AddTableRow () function I declared two variables and looped but the value of "start" is always 1 and does not increase.

    
asked by anonymous 09.05.2017 / 21:55

4 answers

1

You can change the logic a bit, and instead of a counter you count the number of lines at the time of insertion, so you save a bit of code, eg

var maximo = 5;
(function($) {
   AddTableRow = function() {
      var qtd = $("#products-table tbody tr").length;
      //somente insere se a quantidade for menor ou igual a máximo
      if (qtd < maximo) {
         
         var newRow = $("<tr>");
         var cols = "";
         cols += '<td><input class="campo-dinamico" type="text"/></td>';
         cols += '<td>&nbsp;</td>';
         cols += '<td>&nbsp;</td>';
         cols += '<td>&nbsp;</td>';
         cols += '<td>';
         cols += '<button onclick="RemoveTableRow(this)" type="button">Remover</button>';
         cols += '</td>';
         newRow.append(cols);
         $("#products-table").append(newRow);
         resetId();
         return false;
       }
   };    
})(jQuery);

(function($) {
  RemoveTableRow = function(item) {
    var tr = $(item).closest('tr');
    tr.fadeOut(400, function() {
      tr.remove();  
      resetId();
    });
    
    return false;
  }
})(jQuery);
//renova os ids dos campos dinâmicos
function resetId(){
    $('.campo-dinamico').each(function(i){
       $(this).attr('id','campo-' + (i + 1)).val('campo-' + (i + 1));
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="products-table" border="1">
<thead>
<tr>
   <th>Produto</th>
   <th>Código</th>
   <th>Quantidade</th>
   <th>Preço</th>
   <th>Ações</th>
 </tr>
</thead>
<tbody>
 <tr>
   <td><input type="text" id="campo-1" class="campo-dinamico" value="campo-1"/></td>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>&nbsp;</td>
   <td>
     <button onclick="RemoveTableRow(this)" type="button">Remover</button>
   </td>
 </tr>
</tbody>
<tfoot>
 <tr>
   <td colspan="5" style="text-align: left;">
     <button onclick="AddTableRow()" type="button">Adicionar Produto</button>
   </td>
 </tr>
</tfoot>
</table>

For this you need to change some things:

  • The table structure, put the table header in thead , so you can count the exact number of rows in tbody .
  • The% w /% checking the number of rows is in the wrong place, it must be within the if function.
  • The name of the function you remove is incorrect, change AddTableRow to remove
  • 09.05.2017 / 22:15
    1

    Flávio, as many have said you need to put the condition inside the function, but I see that you are having trouble managing dynamically created content in JavaScript.

    So in your case, maybe VueJS might be more practical than jQuery.

    Below is an example using VueJS.:

    var model = { 
      novo: {
        produto: "",
        codigo: "",
        quantidade: "",
        preco: "",
      },
      lista: []
    };
    
    var app = new Vue({
      el: '#tabela',
      data: model,
      methods: {
        deleteItem: function (item) {
          var index = this.lista.indexOf(item)
          this.lista.splice(index, 1);
        },
        novoItem: function (item) {
          if (this.lista.length == 5) {
            alert("Não é possivel ter mais de 5 produtos");
            return;
          }
          if (!item.produto || !item.codigo || !item.quantidade || !item.preco) {
            alert("Todos os campos são obrigatorios");
            return;
          }
          this.lista.push(item);
        }
      }
    });
    input {
      width: 100px;
    }
    <script src="https://unpkg.com/vue"></script><fieldsetid="tabela">
      <legend>
        Hello Wolrd
      </legend>
      <table>
        <thead>
          <tr>
            <th>Indice</th>
            <th>Produto</th>
            <th>Código</th>
            <th>Quantidade</th>
            <th>Preço</th>
            <th>Ações</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in lista">
            <td>{{index}}</td>
            <td>{{item.produto}}</td>
            <td>{{item.codigo}}</td>
            <td>{{item.quantidade}}</td>
            <td>{{item.preco}}</td>
            <td><button v-on:click="deleteItem(item)">Delete</button></td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td></td>
            <td><input type="text" v-model="novo.produto" /></td>
            <td><input type="number" v-model="novo.codigo" /></td>
            <td><input type="number" v-model="novo.quantidade" /></td>
            <td><input type="number" v-model="novo.preco" /></td>
            <td><button v-on:click="novoItem(novo)">Incluir</button></td>
          </tr>
        </tfoot>
      </table>
    </fieldset>
        
    10.05.2017 / 14:29
    0

    I would do something like:

    var inicio = 1, maximo = 5;
    
    function addTableRow(){
       if (inicio <= maximo) {
        var newRow = $("<tr>");
        var cols = "";
        cols += '<td>&nbsp;</td>';
        cols += '<td>&nbsp;</td>';
        cols += '<td>&nbsp;</td>';
        cols += '<td>&nbsp;</td>';
        cols += '<td>';
        cols += '<button onclick="RemoveTableRow(this)" type="button">Remover</button>';
        cols += '</td>';
        newRow.append(cols);
        $("#products-table").append(newRow);
        inicio++;
       }
    }
    
    function removeTableRow(element){
        var tr = $(item).closest('tr');
        tr.fadeOut(400, function() {
         tr.remove();  
        }
        inicio--;
    }
    
        
    09.05.2017 / 22:13
    0

    I have modified only where the counter is applied so as not to run away from what you thought:

    (function($) {
      RemoveTableRow = function(item) {
        inicio--;
        var tr = $(item).closest('tr');
        tr.fadeOut(400, function() {
          tr.remove();
        });
        return false;
      }
    })(jQuery);
    
    var inicio = 1;
    var maximo = 5;
    (function($) {
    
      AddTableRow = function() {
        if (inicio < maximo) {
          inicio++;
          var newRow = $("<tr>");
          var cols = "";
          cols += '<td>&nbsp;</td>';
          cols += '<td>&nbsp;</td>';
          cols += '<td>&nbsp;</td>';
          cols += '<td>&nbsp;</td>';
          cols += '<td>';
          cols += '<button onclick="RemoveTableRow(this)" type="button">Remover</button>';
          cols += '</td>';
          newRow.append(cols);
          $("#products-table").append(newRow);
          return false;
        };
      }
    
    })(jQuery);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableid="products-table">
      <tbody>
        <tr>
          <th>Produto</th>
          <th>Código</th>
          <th>Quantidade</th>
          <th>Preço</th>
          <th>Ações</th>
        </tr>
        <tr>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>&nbsp;</td>
          <td>
            <button onclick="RemoveTableRow(this)" type="button">Remover</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td colspan="5" style="text-align: left;">
            <button onclick="AddTableRow()" type="button">Adicionar Produto</button>
          </td>
        </tr>
      </tfoot>
    </table>

    I put the increment inside the click event and within the condition that checks the line limit, and decrementing the function that removes the line.

        
    09.05.2017 / 22:39