How to send form_tag variables to javascript function? Rails

Asked

Viewed 421 times

1

I am new to web programming and Rails and have the following question:

I have a view that displays a food list and a field to fill with the amount of grams I want from each food. I’d like to exhibit a text_field_tag for every element of the list I own, 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 you put in the fields to a javascript function that multiplies 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 to 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 function calculation result?

Could someone help me?

2 answers

0


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

In the view you can pass some data as attributes in the tags and use the method each_with_index 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 wait for the event to happen, calculate and put into the view by 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";
});

0

If I understood your question correctly, I was able to do something similar using the Gems simple_form and Cocoon (for nested Forms). The latter generates serialized names according to the amount of records in the subform. So you could do something like this 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.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.