bharath
bharath

Reputation: 623

Mathematical calculations using jQuery/Ajax

I have this in my Form

 <%= f.label :price, "price"%> 
<%= f.text_field :price, :size=>20, :id =>"price" %>

<%= f.label :quantity, "Quantity"%>
<%= f.text_field :quantity, :size=>20, :id =>"qty" %>

<%= f.label :amount, "Amount"%>
<%= f.text_field :amount, :size=>20, :id =>"amount"%>

I want {price*quantity} to happen inside the 'amount' field as soon as i enter values inside 'price' and 'quantity' i.e calculations should happen before submit. I am new to jQuery/Ajax, so any help will do. Thanks in advance.

Upvotes: 1

Views: 2233

Answers (1)

thomas
thomas

Reputation: 2578

You can do something like this

$(function() {
    $("#price, #qty").keyup(function() {
        var p = $("#price").val();
        var q = $("#qty").val();
        $("#amount").val(q * p);
    });
});

But you have to give the amount field the id "amount" and not reuse "price" as the id.

Upvotes: 4

Related Questions