user3383794
user3383794

Reputation: 17

how to trigger jquery function when field automatically filled?

I have created an order form with multiple lines and columns Product_id Qty price

Quantity and price are automatically filled out when Product is chosen in a drop down list.

At the end of the form, I have a field that sore the total amount <span id="total"></span>

I made the code below to calculate the total amount of the order but it doesn't work when qty and price are automatically filled. It does work if I type in qty or price

jQuery(function($) {
    $(".qty, .price").change(function() {
        var total = 0;
        $(".qty").each(function() {
            var self = $(this),
                price = self.next(".price"),
                subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10);
            total += (subtotal || 0);
        });
        $("#total").text(total);
    });
});

Upvotes: 0

Views: 1595

Answers (4)

spidermanit
spidermanit

Reputation: 353

You just need to separate you code into a new function such as:

var calculate = function() {
    var total = 0;
    $(".qty").each(function() {
        var self = $(this),
            price = self.next(".price"),
            subtotal = parseInt(self.val(), 10) * parseFloat(price.val(), 10);
        total += (subtotal || 0);
    });
    $("#total").text(total);
};
$(".qty, .price").change(calculate);

Then call it whenever you want.

Upvotes: 1

CSharper
CSharper

Reputation: 5580

Try calling a Function on page load and do it like this.

$( document ).ready(function() {

  YourFunction();


YourFunction() function{

     // insert your code
 }
});

Then you can say

$(".qty, .price").change(function() {
     YourFunction();
}

Upvotes: 0

pazitos10
pazitos10

Reputation: 1709

I don't know if its correct but, have you tried using documnt.load()? you could put the code in a function that you call when page its loaded and when field value has changed.

Upvotes: 1

Milind Anantwar
Milind Anantwar

Reputation: 82231

You can use .trigger('change') or .change() while changing the textbox value from code:

 $(".qty, .price").trigger('change');

or

 $(".qty, .price").change();

For Example:

 $(".qty").val('30').change();  

Upvotes: 1

Related Questions