Change table with javascript javascript

1

I have a dynamically created order table, the user selects the item, the quantity, and whether it is for loan or not, and adds the item to the table.

I needed that by adding an item that is already inserted into the table (for example, the mouse, whose ID is 8) and that the loan column also has the same value, instead of adding a new line to the mouse , increase the amount of the existing row in the table, and I do not know how to do it.

So, when adding a new product, I need to check all the rows in the ID's column if the ID of that product is already inserted, and if the LINE column of that row also has the same value as the one being inserted, if the 2 conditions are true, instead of adding a new row, just increase the amount of the existing row.

<table id="tabela_pedido">
<thead>
  <tr>
   <th>Item</th>
   <th>Quantidade</th>
   <th>Empréstimo</th>
   <th>Ações</th>
  </tr>
</thead>
<tbody>
 <td style="display:none;">8</td>
 <td>Mouse</td>
 <td>2</td>
 <td>Sim</td>
 <td><button class="btn btn-large btn-danger" onclick="RemoveTableRow(this)" type="button">Remover</button></td>
</tbody>
</table>

Where: the first column that is hidden is the ID of the item, the second the name, the third the amount being requested, the third if it is an item for loan or not, and the fourth an action to remove the line

    
asked by anonymous 26.05.2016 / 19:15

1 answer

0

In your case it would be better to control the selected products with an array of objects, for example:

var produtos = [
    { id: 0, nome: "lorem", valor: 0 },
    { id: 1, nome: "lorem 1", valor: 0 },
    { id: 2, nome: "lorem 2", valor: 0 } 
];

And the selected products:

var selecionados = [
    { id: 1, quantidade: 2, emprestimo: true },
    { id: 2, quantidade: 1, emprestimo: false },
];

When adding a new product in the list, it would check for the id if it is already in the list, in which case it only adds the value of the 'quantity' element of the element to 1. Ex.

var id = 1; // id do produto selecionado    
var encontrado = selecionados.find(function(el) {
                     return el.id === id;
                 }); // busca o produto
if (encontrado)
    encontrado.quantidade++;

Then just display the values going through the array in the table.

    
26.05.2016 / 23:14