Multiplying creator input by for

Asked

Viewed 644 times

2

I have this script where I created the for to appear all the records contained in the database where the all products with the same category appear (shows name and value)

and the customer clicks the desired amount and the value appears when clicking appears the trace and then sends to the database

However when clicking on the quantity of the first product the multiplication is made only that the result appears in all other tables and how much I click on the quantity of the second table the multiplication is not made and still keep the result of the first product that happens with the third and the quarter

inserir a descrição da imagem aqui

* how to make each one shape and appear its result. *

<?php
public function listarProduto($sql){
$total = $this->totalRegistros($sql);

for($j=0;$j<$total_prod;$j++){
    $this-> verTudo($sql,$j);

    $sqlRegistro = "SELECT * FROM produto WHERE id='$id'";
    $result = mysql_query($sqlRegistro);
    $idProduto = mysql_result($result, 0, "idProduto");
    $idNomeProduto = mysql_result($result, 0, "idNomeProduto");
    $valor  = mysql_result($result, 0, "valor");
    $action = "op/opcadastro.php";

echo "
<script>
        $(document).ready(function(){
           $('#valor, #qtde').click(function(){
           var valor = $('input[name=valor]').val(); 
           var qtde        = $('#qtde').val(); 

           if(valor == '') valor = 0;
           if(qtde == '') qtde = 0;

          var result = ((valor) * (qtde)).toFixed(2);
          $('.resultado').html(result.replace('.',',').replace(/(\d)(?=(\d{3})+\,)/g, '$1.'));
          });
       });
</script>

<table border='1' cellpadding='0' cellspacing='0' id='tabela'>
<tr><td>Nome do Produto</td>
<td>$idNome</td>
</tr>
<tr><td>Quantidade</td>
<td><input type='number' id='qtde' name='qtde'></td>
</tr>
<tr><td>Valor</td>
<td><input type='hidden' id='qtde' name='qtde'> $valor</td>
</tr>
<tr><td>Resultado</td>
<td><span class='resultado'></span></td>
</tr>
<tr><td colspan='2'>
<form action='$action' method='post' enctype='multipart/form-data'>
                            <input type='hidden' name='idProduto' value='$idProduto'/>
<input type='hidden' name='qtde' value='$qtde'/>
<input type='hidden' name='valor' value='$valor'/>
<input type='hidden' name=acao value='INSERIR' />
                    <input type='submit' value='Adicionar à Lista'>
                        </form></td></tr>
                    </table>";
}
}

?>
  • looking for self the first thing I saw was that you own two fields with id=Qtde

1 answer

3

You need to use classes or other attribute instead of duplicate Ids. This is invalid html. Javascript does not know what part of the DOM (html) is running so using ID in the selectors will always return the first element found and only this. The reason why all results are rewritten is because of $('.resultado').html(...) that searches all classes and changes the value. You only have to search for the '.resultado' of that table you clicked on.

Another thing that doesn’t make sense is to generate Javascript within a PHP loop. You can change Javascript to be independent of the number of rows or number of tables, only using classes and the DOM relation (using the .closest()) to know how to find what you want and calculate.

Changes all the id='qtde' for class='qtde' (or joining the class qtde existing classes if there already are) and then use Javascript like this (only once in the document):

$(document).ready(function() {
    $('.qtde').click(function() {
        var table = $(this).closest('table');
        var valor = table.find('input[name="valor"]').val() || 0;
        var qtde = this.value || 0; // saber o valor do elemento clicado, dando zero caso não tenha valor
        var result = (valor * qtde).toFixed(2);
        var finalResult = result.replace('.', ',').replace(/(\d)(?=(\d{3})+\,)/g, '$1.');
        table.find('.resultado').html(finalResult);
    });
});

Also note that jQuery returns values in format String. The ideal was to convert to integers and not rely on Javascript type conversions. So I suggested you do:

 var result = (parseInt(valor, 10) * parseInt(qtde, 10)).toFixed(2);
  • 1

    +1 why id and class

  • I liked your help. I intendi your explanation and put some things

Browser other questions tagged

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