How to calculate in nested form

Hello i want to calculate between two fields in a nested form.
like Invoice and invoice item.
invoice item have many item, and each item have name, quantity, price and total.
total of that will be quantity * price.

this is the form

<%= form.fields_for :expenseitems do |builder| %>
   <%= render  "expenseitem", form: builder %>
<% end %>

and this is the partial.

  <td class="col-6">
      <%= form.text_field :itemname, class: 'form-control form-control-sm', placeholder: 'Item Name' %>
    <%= form.text_field :itemqty, class: 'form-control itemqty', placeholder: 'Item QTY' %>
    <%= form.text_field :itemprice, class: 'form-control itemprice', placeholder: 'Item Price' %>
    <%# Total price for each item%>
    <%= form.text_field :itemtotal, class: 'form-control  itemtotal', disabled: 'disabled'%>
    <%= form.hidden_field :_destroy, as: :hidden %>
    <%= link_to "#", class: 'btn btn-sm btn-danger text-xs remove-fields' do %>
    <% end %>

i want to total of each item. how can i do this?

thank you

Do you want to calculate it on the server before the form is rendered or In the browser while the user is typing?

1 Like

Thank you for your replay. I want to save that on server, after press update or save. Thank you

This means that in the controller you know both values so in the controller you can sum them up

def update
   object.expressitems....# sum and produce the total

You will have to use javascript and set the value to a hidden field - that way you can avoid server-side calculation