Add up 02 fields from the BD Mysql fields

1

How do I, if the user types the values in 02 fields, the result of that sum automatically appears in the EndType [] 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>";
    .....
}
    
asked by anonymous 29.04.2018 / 23:29

1 answer

2

You can do this by selecting the line of input where the values are being inserted, searching for and summing the values of the first two input s:

// 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><tableborder="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>
    
29.04.2018 / 23:46