Doing price calculation with jQuery within PHP loop

0

I'm doing a shopping simulation page.

I already have the product loop in PHP, now I need to calculate each product by quantity.

Here's the HMTL:

<td width="140"><?= $produto_nome; ?></td>
<td width="160"><?= $produto_descricao; ?></td>
<td width="60"><?= $produto_tamanho; ?></td>
<td width="90">
    <input type="number" id="qtd" name="qtd" min="1" max="99" onChange="MudaLabel('total', this.value)">
    <a href="#">remover</a>
</td>
<td width="120"><span id="preco"><?= $produto_preco; ?></span></td>
<td width="90">
    <label id="total"></label>
</td>

Here's jQuery:

function MudaLabel(LabelID, value){
var Preco = $('#preco').text();

var Total = value * Preco;   //valor de exemplo
document.getElementById(LabelID).innerHTML = Total;

Now think of it as a looping. How do I make each table of this be individually calculated.

This way I did, when I change the amount of other products changes only the value of the first.

    
asked by anonymous 01.02.2016 / 22:38

1 answer

2

If you do this the way it is, all the "span" tags will have the same ID, ie "price". The ID is something that should be unique throughout your HTML because it represents a specific element.

See, the instruction given to the system is to capture the text that is inside the element with the "price" ID:

var Preco = $('#preco').text();

But in your looping, all tags will have the ID "price":

<span id="preco"><?= $produto_preco; ?></span>

Soon there will be more than one element with the ID "price" and when the system tries to get this element through its ID, the first one is returned, so only the first one is updated.

In order to solve your problem, each "span" tag must have its own ID (I assume the "product_id" variable exists in your PHP):

<span id="preco_<?= $produto_id; ?>"><?= $produto_preco; ?></span>

Your "qtd" field must have a unique ID as well as the label that receives the total:

<input type="number" id="qtd_<?= $produto_id; ?>" name="qtd" min="1" max="99" onChange="MudaLabel(<?= $produto_id; ?>)">
<a href="#">remover</a>
//...
<label id="total_<?= $produto_id; ?>"></label>

Note that each element of HTML will have a unique ID consisting of "_" followed by the product ID, so there will be no element with the repeated ID.

Now just change your JavaScript function:

function MudaLabel(id){
    var qtd = $('#qtd_' + id).val()
    var Preco = $('#preco_' + id).text();

    var Total = qtd * Preco;   //valor de exemplo
    document.getElementById('total_' + id).innerHTML = Total;
    //...
}
    
01.02.2016 / 23:52