Generate array with table contents with jquery

0

Hello

I'm trying to retrieve the elements of a table and move to a jquery array that will be used in ajax

I create the td dynamically:

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

        cols += '<td class="tdProductId" id='+ $("#product option").attr("id") +'>'+ $("#product option").text() +'</td>';
        cols += '<td class="tdProductAmount">'+ $("input[name=amount]").val() +'</td>';
        cols += '<td class="tdProductPrice">'+ $("input[name=price]").val() +'</td>';
        cols += '<td class="tdProductTotal">'+ $("input[name=price]").val() * $("input[name=amount]").val() +'</td>';
        cols += '<td>';
        cols += '<a href="#" class="removeProduct">Remover</a>';
        cols += '</td>';

        newRow.append(cols);
        $("#input_stock_product").append(newRow);

The problem is to recover the attr of one td and the text of the other and by in an array What I've tried to do, however, it does not create other indexes in the array, and ends up putting the values together:

        var productsData = { 
            id_product: $(".tdProductId").attr("id"),
            amount:  $(".tdProductAmount").text(),
            price: $(".tdProductPrice").text(),
            total: $(".tdProductTotal").text()
        };

This way it returns me an object, eg:

Object {id_product: "137", amount: "12", price: "11", total: "132"}
    
asked by anonymous 17.04.2016 / 01:00

2 answers

1

First you need to add a class to tr. Then use the each method in that class to get each row added, and treat it with the $ (this) reference.

Exemplifying: link

    
17.04.2016 / 01:14
1

You can do this:

    var arrayDeLinhas = [];

    $("tbody > tr").each(function(index,tr){
        arrayDeLinhas.push(  { 
            id_product: $(tr).find(".tdProductId").attr("id"),
            amount:  $(tr).find(".tdProductAmount").text(),
            price: $(tr).find(".tdProductPrice").text(),
            total: $(tr).find(".tdProductTotal").text()
        });
    });

    console.log(arrayDeLinhas);

Notice that the search for rows is done through a tbody element. If you have not used this tag (should) in your table. Swap the table handle. Assuming the selector you used to add a row, be the table identifier, use this:

    $("#input_stock_product > tr").each(function(index,tr){...
    
17.04.2016 / 02:48