2016-08-26 102 views
0

我得到一个表单,当用户更改某些东西并重新计算所有值时更新自己,但有些值是从php会话中获取的,所以它必须在页面加载时更新并计算正确的值就像onchange()一样。加载jQuery执行函数()

$(document).ready(function() { 
    $('.qty').change(function() { 
     update_amounts(); 
    }); 

    update_amounts(); //<--- must to be executed on document.ready() 
}); 

function update_amounts() { 
    var sum = 0.0; 
    $('#myTable > tbody > tr').each(function() { 

     var qty = $(this).find('option:selected').val(); 
     var price = $(this).find('.price').val(); 
     var amount = (qty*price) 
     sum+=amount; 
     $(this).find('.amount').text(''+amount); 
    }); 
    //calculate the total to sum 
    $('.total').val(sum); 
    //calculate total + shipping and add VAT 
    var shipping = $('.shipping').val(); 
    var total = $('.total').val(); 
    var vat = $('.vat').val(); 
    //calculate vat 
    var vat_value = ((total*vat)/100); 
    //calculate grand total 

    sub_total = (parseFloat(total)+parseFloat(shipping)).toFixed(2); 

    var grand_total = (parseFloat(sub_total)+parseFloat(vat_value)).toFixed(2); 

    $('.grandTotal').val(grand_total); 
    $('.modalTotal').val(grand_total); 
} 

但是,当我不改变的document.ready();一定的价值和

有人能解释为什么只执行该代码?以及如何才能在载入时启动update_amounts();功能?

+4

似乎正确。有什么错误或什么? – eisbehr

+0

所示的代码应该在文档准备好时运行update_amounts ...您是否遇到任何控制台错误? –

+0

不......在控制台中没有错误,这就是为什么我找不到解决方案。 – andreaem

回答

0

我已经解决使用

$(window).load(function() { update_amounts(); }); 

这将调用函数update_amounts();窗口加载时的问题。