Search code examples
ruby-on-railsrubyruby-on-rails-2

How can i multiple 2 text_field_tags?


I'm trying to create a type of change from DOLARS to Euros

Something like this :

  • A text_field where it shows my total sum of dolars.
  • Another text_field where i can type a number.
  • Another text_field where shows the total sum of dolars * the number typed

This is my structure

  ______________        _____________       ______________
  |____value____|  *   [sum_of_dolars]  =  [dolar_to_euro]

This is my table with 3 columns

 Policies
   |id|   |mount|   |type_money|  .....all my columns are Integer
     1      100        1
     2      120        1
     3       80        1
     4      120        1

This is my controller

class PolicyManagement::PolicyController < ApplicationController

  def calculator
    @policies = Policy.find(:all)
    @dolar= Policy.sum(:mount, :conditions=>["type_money = '1' "])
    @dolar_to_euro= @dolar * @type_of_change
  end

end

This is my model

class Policy < ActiveRecord::Base
     #nothing
end

This is my view

<%= form_tag('/calculator') do -%> 
  <% text_field_tag "dolars",@dolar %>
  <% text_field_Tag "type_of_change", @change %>
  <% text_field_tag "dolar_to_euro",@dolar_to_euro %>
  <% submit_tag "Results" %> 
<% end -%> 

I will really appreciate all help please,somebody can help me with this please?


Solution

  • You need to use javascript like this in your view

        <script type="text/javascript">
            function doMath()
            {
              // Capture the entered values of two input boxes
              var euro = document.getElementById('euro').value;
    
              var euro = Math.floor(parseFloat(euro) * 100) / 100;
              document.getElementById('euro').value = euro.toFixed(2);
    
              var cost = document.getElementById('cost').value;
              var dolar =document.getElementById('dolar').value;
    
              // Add them together and display
              var subtotal = Math.floor(parseFloat(euro) * 100) / 100 * Math.floor(parseFloat(costo) * 100) / 100;
              document.getElementById('subtotal').value = subtotal.toFixed(2);
    
              var total = parseFloat(subtotal) + parseFloat(dolar);
              document.getElementById('total').value = total.toFixed(2);
            }
        </script>
    
       <%= text_field_tag "euro", @euro  %>
       <%= text_field_tag "dolar", @dolar  %>
       <%= text_field_tag "cost", :onchange=>"doMath();"  %>
       <%= text_field_tag "subtotal", params[:subtotal] %>
       <%= text_field_tag "total", params[:total]  %>
    

    Your controller

     def calculator
       @policies = Policy.find(:all)
       @dolar= Policy.sum(:mount, :conditions=>["type_money = '1' "])
       @euro=  Policy.sum(:mount, :conditions=>["type_money = '2' "])
     end
    

    Hope this will help you