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.

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

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.update(object_params)
   object.expressitems....# sum and produce the total
end

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