2016-04-04 14 views
0

私は、食品アイテムと衣類アイテムの合計を個別に(ユーザーが各アイテムの値を入力すると)動的に更新するコードを持っています。私は合計費用を表示したい(衣類+食糧の合計)。私はそれを動的に更新したい。個々の合計(衣類/食べ物)については、私は.keyupを使用しました。キーを押すことなく、衣服の合計と食べ物の合計が満たされるので、キーアップを使用して総費用を動的に埋めることはできません。私はそれをする方法を見つけるのが難しいです。これは私がその特定のセクションのために書いたコードです:動的に入力された値の合計

以下
$("#total_food, #total_clothes").on("input", function() { 
    var sum = $("#total_food").val()+$("#total_clothes").val(); 
    $("#total_costs").val(sum); 
}); 

は私の全体のコードです:

<table> 
    <tr> 
     <td>(1) Milk 2</td> 
     <td><input type="text" class="price_food"></td> 
    </tr> 
    <tr> 
     <td>(2) Eggs</td> 
     <td><input type="text" class="price_food"></td> 
    </tr> 
    <tr> 
     <td>Total Cost of Food</td> 
     <td><input type="text" disabled="disabled" id="total_food"></td> 
    </tr> 
    <tr> 
     <td>Shoes </td> 
     <td><input type="text" class="price_clothes"></td> 
    </tr> 
    <tr> 
     <td>Pants</td> 
     <td><input type="text" class="price_clothes"></td> 
    </tr> 
    <tr> 
     <td>Total Cost of Clothes</td> 
     <td><input type="text" disabled="disabled" id="total_clothes"></td> 
    </tr> 
    <tr> 
     <td>Total Costs</td> 
     <td><input type="text" disabled="disabled" id="total_costs"></td> 
    </tr> 
</table> 
$(document).ready(function() { 
    $('.price_food').keyup(function() { 
     var sum = 0; 
     $('.price_food').each(function() { 
      sum += Number($(this).val()); 
     }); 
     $('#total_food').val(sum); 
    }); 

    $('.price_clothes').keyup(function() { 
     var sum = 0; 
     $('.price_clothes').each(function() { 
      sum += Number($(this).val()); 
     }); 
     $('#total_clothes').val(sum); 
    }); 

    $("#total_food, #total_clothes").on("input", function() { 
     var sum = $("#total_food").val() + $("#total_clothes").val(); 
     $("#total_costs").val(sum); 
    }); 
}); 
+0

どのように動的に埋められますか? – j08691

+0

sum - total_foodとtotal_clothesは、ユーザーが各項目の量を入力すると(.keyupを使用して)動的に更新されます。 – kbt

答えて

0

全体の合計が別々に機能して、自分のクラスの入力のそれぞれの後に、それを呼び出してくださいこのような関数:

$(document).ready(function() { 
    $('.price_food').keyup(function() { 
     var sum = 0; 
     $('.price_food').each(function() { 
      sum += Number($(this).val()); 
     }); 
     $('#total_food').val(sum); 
     calculatetotalcosts(); 
    }); 

    $('.price_clothes').keyup(function() { 
     var sum = 0; 
     $('.price_clothes').each(function() { 
      sum += Number($(this).val()); 
     }); 
     $('#total_clothes').val(sum); 
     calculatetotalcosts(); 
    }); 

    function calculatetotalcosts(){ 
     var totalcost = Number($("#total_food").val()) + Number($("#total_clothes").val()); 
     $("#total_costs").val(totalcost); 
    }; 
}); 

ワーキングjSFiddle:https://jsfiddle.net/rdawkins/qryx2kmm/4/

関連する問題