Make price calculation with jQuery inside PHP loop

Asked

Viewed 411 times

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 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 the 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 to be individually chalked.

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

1 answer

2


If you do it 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 as it represents a specific element.

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

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

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

<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 the respective ID, the first found is returned, so only the first one is updated.

To solve your problem, you need each "span" tag to have its own ID (I’ll assume that there is a "producto_id" variable in your PHP):

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

Your "Qtd" field needs to have a unique ID as well, as does the label that gets 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 HTML element now has a unique ID composed 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;
    //...
}
  • Perfect, Philip! It was more a logical question even, that I had not thought. Saved me! Thank you very much!

Browser other questions tagged

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