Sum 02 fields of the fields coming from BD Mysql

Asked

Viewed 31 times

1

How do I, the user enter the values in 02 fields the result of this sum automatically appear in the Final Value field[]? These fields are coming from the database.

while($peListar = mysqli_fetch_object($sqlListar){
    .....
    $listar .= "<td style='".$fundo."'><input type='text' name='ValorI[]'  class='md-form-control'  value=''></td>";
    $listar .= "<td style='".$fundo."'><input type='text' name='ValorII[]' class='md-form-control' value=''></td>";
    $listar .= "<td style='".$fundo."'><input type='text' name='ValorFinal[]' class='md-form-control' value=''></td>";
    .....
}

1 answer

2


You can do it this way by selecting the input where the values are being entered, searching and summing the values of the first two inputs:

// input com name iniciado por "ValorI", ou seja,
// vai pegar tanto o "ValorI" quanto o "ValorII"
$("[name^='ValorI']").on("input", function(){
   
   var parent = $(this).closest("tr"); // seleciona a linha TR
   
   // converto os valores em número. Se for vazio, assume 0
   var valor1 = parseFloat($("[name='ValorI[]']", parent).val()) || 0;
   var valor2 = parseFloat($("[name='ValorII[]']", parent).val()) || 0;
   
   // insiro a soma no campo "ValorFinal[]" da respectiva linha
   $("[name='ValorFinal[]']", parent).val(valor1+valor2);
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="1">
   <tr>
      <td><input type='text' name='ValorI[]'  class='md-form-control'  value=''></td>
      <td><input type='text' name='ValorII[]' class='md-form-control' value=''></td>
      <td><input type='text' name='ValorFinal[]' class='md-form-control' value=''></td>
   </tr>
   <tr>
      <td><input type='text' name='ValorI[]'  class='md-form-control'  value=''></td>
      <td><input type='text' name='ValorII[]' class='md-form-control' value=''></td>
      <td><input type='text' name='ValorFinal[]' class='md-form-control' value=''></td>
   </tr>
   <tr>
      <td><input type='text' name='ValorI[]'  class='md-form-control'  value=''></td>
      <td><input type='text' name='ValorII[]' class='md-form-control' value=''></td>
      <td><input type='text' name='ValorFinal[]' class='md-form-control' value=''></td>
   </tr>
</table>

  • Hello dvd, it worked the way it went, but forgive me, I forgot to mention a detail. The total value of the sum will be divided by 2 I put it as follows: (value1+value2)/2, but he only calculated the first field.

  • 1

    Put it like this: $("[name='ValorFinal[]']", parent).val((valor1+valor2)/2); the result will be, for example: valor1 = 100 + valor2 = 60, summing up = 160, divided by 2, outworking = 80.

  • 1

    Sorry again dvd, it worked yes. It was a mistake of mine here. Thank you

Browser other questions tagged

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