php - jQuery live calc multirow input

564

This is my code:

<?php
  for($i=1;$i<10;$i++){ 
    echo '<input type="text" >';
    echo '<input type="text" >';
    echo '<input type="text" disabled id="result'. $i .'"><p>';
  }
    echo '<input type="text" disabled id="total"><p>';
  ?>

and jQuery:

$(document).ready(function(){
    $(".count").keyup(function(){
        for (var i = 0; i < 10; i++) {
            var val1 = +$(".value"+ i).val();
            var val2 = +$("."+ i +"value").val();
            $("#result" + i).val(val1*val2);
        }
   });
});

$(document).ready(function(){
    $(".count").keyup(function(){
        for (var i = 0; i < 10; i++) {
            var vala = 0;
            vala += +$("#result"+ i).val();
            }
            $("#total").val(vala);
   });
});

First part of code works great. Return multiplication two inputs toid=result$i.

I have a problem with last oneid=total. It should return sum of all result X inputs but now only return the last multiplication. Do You have any idea what's wrong?

493

Answer

Solution:

You can simplify your code by grouping the relatedinput elements together in a containingdiv, using DOM traversal to retrieve the needed values, and joining the twofor loops together. Try this:

<div >
  <input type="text" />
  <input type="text" />
  <input type="text" disabled />
</div>
<!-- repeat the above as needed. Note that the incremental id is no longer needed -->

<p>
  <input type="text" disabled id="total" />
</p>
$(document).ready(function(){
    $(".count").keyup(function() {
        var total = 0;
        $('.group').each(function() {
            var $group = $(this);
            var valA = +$group.find('.valueA').val() || 0;
            var valB = +$group.find('.valueB').val() || 0;
            var result = valA + valB;
            total += result;
            $group.find('.result').val(result);
        });
        $("#total").val(total);
   });
});

354

Answer

Solution:

That is because you have defined variablevala to 0 in for loop. which should be outside for loop:

$(".count").keyup(function(){
    var vala= 0;
    for (var i = 0; i < 10; i++) {
        vala += $("#result"+ i).val();
    }
    $("#total").val(vala);
 });

People are also looking for solutions to the problem: mysql warning during php json script

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.