Generate array with table contents with jquery

Asked

Viewed 726 times

0

Hello

I am trying to recover the elements of a table and pass 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 retrieve the attr from one td and the text from the other and put in an array What I tried to do, however, it n creates other indexes in the array, and ends up joining the values all together:

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

This way it returns me an object, ex:

Object {id_product: "137", amount: "12", price: "11", total: "132"}

2 answers

1


First you will need to add a class to tr. Then use each method in that class to pick up each added line, and treat it with the $(this).

Exemplifying: https://jsfiddle.net/64azsg33/

  • have any idea how I would insert this array into a table with codeIgniter with ajax?

  • Yes, but the answer is extensive. Can you ask a new question? So we can help more users who have the same question

  • http://answall.com/questions/123911/inserir-um-array-com-codeigniter-e-ajax

1

You can do it like 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);

Note that the line search is done through a tbody element. If you have not used this tag(Should) in your table. Switch to the table identifier. Assuming the selector you used to add a row, is the table identifier, use this way:

    $("#input_stock_product > tr").each(function(index,tr){...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.