2016-08-26 100 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();窗口加載時的問題。