How to send form_tag variables to javascript function? Rails

1

I'm new to web programming and rails and I have the following question:

I have a view that displays a list of foods and a field to fill with the amount of grams I want from each food. I would like to display a text_field_tag for each element of the list I have, something like:

<% @alimentos.each do |alimento| %>
    <%= text_field_tag :alimento %>
    <%= label_tag(:alimento, "#{alimento.nome}: #{alimento.preco} reais a grama" )%>
<% end %>'

However, I would like to send the amount I put in the fields for a javascript function that would multiply the price by the value I entered and then display the calculated total value in the view.

Unfortunately I have no idea how to do this: How do I create a text_field_tag with a different symbol for each iteration of each ? How to send the values that fill the fields to the javascript function, where to create the javascript function and how to display the result of the function calculation?

Could anyone help me?

    
asked by anonymous 27.11.2016 / 06:23

2 answers

0

When you enter the quantity there are several events that can trigger the calculation, you need to know when you want to calculate. When is he typing? When to click off text_field? When you click a button to calculate? Etc.

In the view you can pass some data as attributes in the tags and use the each_with_index method to create each tag with a different id.

<% @alimentos.each_with_index do |alimento, i| %>
    <%= text_field_tag :alimento, class: 'quantidade', data-id: i %>
    <%= label_tag(:alimento, "#{alimento.nome}: #{alimento.preco} reais a grama", id: 'total-#{i}', "data-preco": alimento.preco, "data-nome": alimento.nome) %>
<% end %>

So in JavaScript you expect the event to happen, calculate it and put it in the view, taking the attribute data.

//exemplo para cacular quando o foco sair da text_field
$("body").on("focusout", ".quantidade", function() {
  // this será o text_field que saiu do foco
  var id = this.getAttribute("data-id");
  var value = this.value;
  var preco = document.getElementById("total-" + id).getAttribute("data-preco");
  var nome = document.getElementById("total-" + id).getAttribute("data-nome");
  document.getElementById("total-" + id).textContent = nome+": " + (preco*value) +" reais a grama";
});
    
25.12.2016 / 13:33
0

If I understood your question well, I was able to do something similar using the simple_form and cocoon (for nested forms) gems. The latter generates serialized names based on the number of records in the subform. So you could do something of the sort in the view:

<td><%= f.input :alimento_quantidade, :input_html => {:onChange => customFunction();'} %></td>

This coffeescript / javascript function would do the calculations and update a totals field.

    
03.12.2016 / 12:35