DrDuty
DrDuty

Reputation: 15

How to iterate through a table with dynamically created tr elements

i have a tr table which gets dynamically created and a total sum at the bottom part (total is not created dynamically).

var tmp = '<tr id="mytable"> <td id="warenid">'+data1.id+'</td> <td id="Bezeichnung">'+data1.title+'</td>  <td id="preis">'+prc+'€</td> <td><select id="menge" name="maximum10">';
tmp += '<option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option>';
tmp += '<option value="5">5</option> <option value="6">6</option> <option value="7">7</option> <option value="8">8</option> <option value="9">9</option> <option value="10">10</option>';
tmp += '</select></td><td class="su" id="summe">'+prc+'</td> <td><a id="removeBestellung" class="btn1" type="button"><i class="fa fa-trash" aria-hidden="true"></i></a> </td>'; //removebestellung kommt später DONT FORGET
tmp += '</tr>';
$("#upper").after(tmp);
}

$(".total").append(sum+"€");

now i want to iterate through the created tables (which are definitly more than 1 ) and update the sum of each row. at last i also want to count all sums and replace the total sum. i tried this:

$( "select" ).change(function() {
    var sv = parseInt($(this).val());
    alert( "wert dropdown:" + sv );
    var newsum = 0;
    $("#mytable").each(function () {
        var preis_str = $(this).find("td").eq(2).html();
        var preis = parseInt(preis_str.slice(0, preis_str.length  - 1));
        alert("preis ohne euro " + preis);
        $(this).find("td").eq(4).html(preis * sv + "€");
        newsum = newsum + (preis * sv);
    })
    $(".total").html(newsum +"€");
});

The problem is, only the first row's sum gets updated and the total sum also refreshes depending on the first row. how can i iterate through all the rows in the dynamic table?

html table looks like this:

<p id=msg2 style="color:red; text-align: center;"></p>
<table id="myTable">
    <thead>
        <tr>
            <th colspan="7">Warenkorb</th>
        </tr>
    </thead>
    <tbody id="table">
        <tr id="upper">
            <td>ID</td>
            <td>Bezeichnung</td>
            <td>Preis</td>
            <td>Menge</td>
            <td>Summe</td>
            <td>Aktion</td>
        </tr>
        <tr>
            <td> </td>
            <td> </td>
            <td> </td>
            <td>Gesamt Preis:</td>
            <td class="total"></td> 
            <td> </td>
        </tr>
    </tbody>
</table>

Upvotes: 0

Views: 1034

Answers (1)

Cookie1980
Cookie1980

Reputation: 108

An ID occurs only one time. You could change your table row (tr) item and add the same class to it (for example class="myTableClassCalc"). Then you can iterate through it by

$(".myTableClassCalc").each(function () {

Upvotes: 1

Related Questions