Mathematical calculations using jQuery/Ajax

2020-07-30 03:08发布

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.

1条回答
我只想做你的唯一
2楼-- · 2020-07-30 03:31

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.

查看更多
登录 后发表回答