I have an order page where I need to get all product prices and apply some calculations to find out the final price.
I have done all these calculations and displayed the results there using button click event by jQuery.
But whenever I update the input fields, I need to click on the button to update previously calculated result and show new one.
How can I’m done this without button click? If any change in the whole content happened, I need to trigger the button click automatically.
If it is possible to do via Ajax, Can you please help me?
Please find my current jQuery code given below.
//Update data corresponding to change in value of days field
$(document).on('change', '#order-edit-extracost', function(e) {
var days = $('#order-edit-extracost').val();
var cost = (parseFloat(days) * 0.5).toFixed(2);
$('#order-edit-extracost-sum').val(cost);
})
// Order page Price calculations
$(document).on('click', '#calculate-cost', function(e) {
var prev_cost = $('.total-prev').html();
var prev_cost_float = parseFloat(prev_cost.match(/-?(?:d+(?:.d*)?|.d+)/)[0]);
var wastetype_sum = 0;
//find sum of all wastetype rows
$( '.order-wastetypeRow' ).each(function( index ) {
var wastetype_price = $(this).find('#order-edit-wasteprice').val();
prev_cost_float = parseFloat(prev_cost_float) + parseFloat(wastetype_price);
});
//calculate VAT and add it to the sum
var extra_cost = $('#order-edit-extracost-sum').val();
var final_cost = (parseFloat(prev_cost_float) + parseFloat(extra_cost)).toFixed(2);
$('.est-cost').html("CHF "+final_cost);
var vat_in_float = parseFloat(final_cost);
var vat_amount = (vat_in_float * 0.077).toFixed(2);
$('.final-vat').html("CHF "+vat_amount);
var total = (parseFloat(final_cost) + parseFloat(vat_amount)).toFixed(2);
//show calculated costs
$('.final-amount').html("CHF "+total);
$('#finalcost-layout').show();
$('.submit-cost').show();
});
2
Answers
you can add below trigger function inside of on change event method.
like below
Okay so first of all I just want to point out that there is a much more convenient way of attaching event listeners to elements in jQuery. Like so:
Now to answer your question, as @freedomn-m said, Ajax is generally for making calls to a server/service. What you want can be achieved without it. So first off, you should make a function that does the calculation, like so:
Next, in order to attach the input fields to the function, you can add the
oninput
attribute to the HTML syntax, like so:Or, you could use a selector that is common to the elements, like the
class
, and attach theinput
event listener by looping through them. Like so:What the
input
event will do is that it will be triggered every time something is input to the field.