dionell dionell - 2 months ago 15
PHP Question

How to calculate automatically using jQuery base on PHP rows?

When I'm trying to place a value in each input type the jQuery function, it works, but in the second row value that I place in the second input, the answer appears in the first row. How can I separate the answer of the another row?

**script**
$('#txt3').keyup(function(){
var textone;
var texttwo;
var textthree;
textone = parseFloat($('#txt1').val());
texttwo = parseFloat($('#txt2').val());
textthree = parseFloat($('#txt3').val());
var result = textone + texttwo + textthree;
$('.result').val(result.toFixed(3));


});


my html


<td class="td-encode"> <input type="text" class="td-input" id="txt1" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
<td class="td-encode"> <input type="text" class="td-input" id="txt2" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
<td class="td-encode"><input type="text" class="td-input" id="txt3" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
<td class="td-encode" id="result_td">
<input type="text" class="result" name="total" disabled />
</td>


Result
enter image description here

Answer

You can try this replacing ID with class:-

HTML

 <tr>
   <td class="td-encode"> <input type="text" class="td-input" class="txt1" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
   <td class="td-encode"> <input type="text" class="td-input" class="txt2" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
   <td class="td-encode"><input type="text" class="td-input" class="txt3" name="txtgrade" onkeyup="sum()" maxlength="2"/></td>
   <td class="td-encode" class="result_td">
      <input type="text" class="result" name="total" disabled />
   </td>
</tr>

JS:

$('.txt3').keyup(function() {
    var textone;
    var texttwo;
    var textthree;
    textone = parseFloat($(this).closest('tr').find('.txt1').val());
    texttwo = parseFloat($(this).closest('tr').find('.txt2').val());
    textthree = parseFloat($(this).closest('tr').find('.txt3').val());
    var result = textone + texttwo + textthree;
    $(this).closest('tr').find('.result').val(result);
});
Comments