Search code examples
phpjqueryinputmultirow

jQuery live calc multirow input


This is my code:

<?php
    for($i=1;$i<10;$i++){ 
        echo '<input type="text" class="count value'. $i .'">';
        echo '<input type="text" class="count '. $i .'value">';
        echo '<input type="text" disabled="disabled" id="result'. $i .'"><p>';
    }
        echo '<input type="text" disabled="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 to id=result$i.

I have a problem with last one id=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?


Solution

  • You can simplify your code by grouping the related input elements together in a containing div, using DOM traversal to retrieve the needed values, and joining the two for loops together. Try this:

    <div class="group">
        <input type="text" class="count valueA" />
        <input type="text" class="count valueB" />
        <input type="text" class="result" disabled="disabled" />
    </div>
    <!-- repeat the above as needed. Note that the incremental id is no longer needed -->
    
    <p>
        <input type="text" disabled="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);
       });
    });
    

    Example fiddle