Index in JavaScript

1

I have a table where I can add rows dynamically, every time I click the button I add a new row to fill the field, my first row comes with index 0

<td><input type="text" name="data[Ticket][0][descricao_ticket]" size="20" placeholder="Informe aqui"></td>

My first information I normally write to the database, but when I need to add a new precise line go in JS and change the index 0 to 1 so that it does not overwrite the information, how do I let this index increase by itself when requesting a new line? Do not handle too much of javascript

(function($) {
    remove = function(item) {
      var tr = $(item).closest('tr');

      tr.fadeOut(400, function() {
        tr.remove();  
      });

      return false;
    }
  })(jQuery);

(function($) {
    AddTableRow = function() {

      var newRow = $("<tr>");
      var cols = "";
      //var indice = 0;

      cols += '<td><input type="text" name="data[Ticket][1][descricao_ticket]" size="20" placeholder="Informe aqui"></td>';

      cols += '<td>';
      cols += '<button type="button" class="btn btn-danger" onclick="remove(this)">Remover</button>';
      cols += '</td>';

      newRow.append(cols);
      $("#details-table").append(newRow);

      return false;
    };
  })(jQuery);
    
asked by anonymous 26.11.2017 / 18:25

1 answer

1

You can count how many elements input to id #details-table have and adding +1 in total:

var indice = $("#details-table input[type='text']").length+1;

And concatenate the variable:

cols += '<td><input type="text" name="data[Ticket]['+indice+'][descricao_ticket]" size="20" placeholder="Informe aqui"></td>';

Tip

You can concatenate the cols variable as follows to wipe the code:

cols += '<td><input type="text" name="data[Ticket]['+indice+'][descricao_ticket]" size="20" placeholder="Informe aqui"></td>'
+'<td>'
+'<button type="button" class="btn btn-danger" onclick="remove(this)">Remover</button>'
+'</td>';
    
26.11.2017 / 18:37