Select cell data from a column with jquery

1

I have the following table

<table class="table table-hover table-secondary mt-1 table-responsive">
     <thead>
         <tr>
             <th>Producto</th>
             <th>Cantidad</th>
             <th>Sub Total Efectivo</th>
             <th>Sub Total Tarjeta</th>
         </tr>
     </thead>
     <tbody id="CarroDeCompra">
         <tr>
             <td>Nombre</td>
             <td>Cantidad</td>
             <td>Efectivo</td>
             <td>Tarjeta</td>                                       
         </tr>
     </tbody>
 </table>

What I want is to count the amounts in the second column, which says quantity.

I searched the Internet and found this code, but it would not be working:

function ContarProductos() {
    let cantidad =0;
    ('#CarroDeCompra td').find('td:eq(1)').each(function() {

    //obtenemos el valor de la celda
    valor = $(this).html();

    //sumamos, recordar parsear, si no se concatenara.
    cantidad += parseInt(valor)
    });

    return cantidad;
}

Can anyone give me any advice? Thank you very much from now!

    
asked by GALS 19.11.2018 в 15:32
source

2 answers

0

You can use this function:

function contar(columna){
    let cantidad = 0;
    $('#CarroDeCompra').find('td:nth-child('+columna+')').each(function(){
        cantidad += +($(this).text());
    });
    return cantidad;
}

contar(2); // Contamos todos los valores de la segunda columna.

To select the column n we use :nth-child(n) in this case n is 2, since the column we want to add is the second one. Then, and assuming that you only have integers in that column, you can use +valor to transform a value to an integer.

    
answered by 19.11.2018 / 15:54
source
0

Test:

$('#CarroDeCompra').find('td:eq(1)').each(function(){

Without the td

    
answered by 19.11.2018 в 15:43