自动计算文本框的值

时间:2015-05-20 07:08:50

标签: javascript

你能帮忙自动计算价格总额吗? http://chocolatehillsadventurepark.com/reservation.php

我的代码会像这样:

<script language="JavaScript">
$('#num_chicken'), $('#num_chicken').on('keyup',function(){
    var tot = $('#price_chicken').val() * this.value;
    $('#total_chicken').val(tot);
});

$('#num_fish'), $('#num_fish').on('keyup',function(){
    var tot = $('#price_fish').val() * this.value;
    $('#total_fish').val(tot);
});

</script>

依旧.....

希望您能立即做出回应。 谢谢!

1 个答案:

答案 0 :(得分:0)

您需要将这些内容放在$( document ).ready(function() {});

$(document).ready(function () {
    $('#num_chicken').on('keyup', function () {
        var tot = $('#price_chicken').val() * this.value;
        $('#total_chicken').val(tot);
    });
    $('#num_fish').on('keyup', function () {
        var tot = $('#price_fish').val() * this.value;
        $('#total_fish').val(tot);
    });

});  

upDate:计算总计
您可以使用以下代码计算总计

function calculateGrandTotal() {
    var grandTotal = 0;
    $('table tbody tr td:nth-child(4) input').each(function (index) {
        grandTotal += parseInt($(this).val());
    });
    $('#grand_total').val(grandTotal);
}  

你需要在每个.on('keyup', function () {之类的

结束时调用它
$('#num_chicken').on('keyup', function () {
    var tot = $('#price_chicken').val() * this.value;
    $('#total_chicken').val(tot);
    calculateGrandTotal();   // add this
});
$('#num_fish').on('keyup', function () {
    var tot = $('#price_fish').val() * this.value;
    $('#total_fish').val(tot);
    calculateGrandTotal();   // add this
});