Multiplying input creator by for

2

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

and the client clicks the desired quantity and the value appears when clicking the result appears and then sends it to the database

But when I click on the quantity of the first product the multiplication is done so that the result appears in all the other tables and when I click on the quantity of the second table the multiplication is not done and still maintains the result of the first product this happens with the third and fourth

*Howtomakeeachonemultiplyandshowitsresult.*

<?phppublicfunctionlistarProduto($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>";
}
}

?>
    
asked by anonymous 15.03.2016 / 21:00

2 answers

2

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

Another thing that does not make sense is to generate JavaScript within a PHP loop. You can change the JavaScript to be independent of the number of rows or number of tables, only using classes and the relationship of the DOM (using the .closest() ) to find out how to find what you want and calculate.

Change all id='qtde' to class='qtde' (or joining the class qtde to existing classes if there is already) and then use JavaScript like this (once only 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 you values in String format. Ideally it was converters for integers and not rely on JavaScript type conversions. So I suggested you do:

 var result = (parseInt(valor, 10) * parseInt(qtde, 10)).toFixed(2);
    
15.03.2016 / 21:10
0
<script>
                $(document).ready(function() {
                    $('.qtde').click(function() {
                        var table = $(this).closest('table');
                        var valor = table.find('input[name="rcPrecoUnit"]').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('span[name=resultado]').html(finalResult);
                        table.find('input[name=resultado]').val(finalResult);//aqui pra poder ir pro banco de dados

                    }); 
                });
            </script>

But I do the first multiplication of right in the first repeats in the second table. So when I change the value of the second table the calculation is done.

How do I not see the result of the previous mutiplication?

    
17.03.2016 / 00:51