0

I have ajax rails no database form calculator. It works well, but it behaves very strange. I will try to explain it.

I go to /interest_calculator page

fill_in @first_0 with 10

fill_in @second_0 with 100

I get result equal to:

Number 50 from number 100 = 50%

Then I go to root page

Go back to /interest_calculator

Reload page and my form is pre-filled with previous value. I believe it is buggy behavior. My JavaScript knowledge is very basic, so detailed response would be very helpful.

InterestCalculator controller:

class InterestCalculatorController < ApplicationController

  def index
    @result_0 = 0
  end

  def new

    respond_to do |format|
      format.html { render 'index.html.erb' }
      format.js
    end 

    # If accepted parameter is integer, then it shows in view as 5, when it
    # is float, it shows as 5.1  
    @first_0   = params[:a_0].to_f % 1 != 0 ? params[:a_0].to_f : params[:a_0].to_i
    @second_0  = params[:b_0].to_f % 1 != 0 ? params[:b_0].to_f : params[:b_0].to_i

    # How many percent is number from the number 
    number_to_number(@first_0, @second_0) 

  end

 private 

   def number_to_number(a = 0, b = 0)   
    # If the first number is zero, it sends 0% answer. If the second number is zero 
    # and the first number is nonzero, it sends infinity. Otherwise simple formula calculation.
    if a.zero?
      @result_0 = 0
    elsif b.zero?
      @result_0 = "infinity"
    else
      @result_0 = a.to_f / b.to_f * 100
    end 
  end
end

My view index.html.erb

  <div id="interest_calculator">
    <%= form_for :interest_calculator, url: { action: :new }, method: :get, remote: true do |f|   %>
      <p>Сколько % составляет число</p>
      <%= number_field_tag :a_0, params[:a_0], step: :any, id: "first_number_0" %>
      <p>от числа</p>
      <%= number_field_tag :b_0, params[:b_0], step: :any, id: "second_number_0" %>
      <%= f.submit 'Calculate!', id: "number_to_number" %>
    <% end %>

    <% unless @result_0.nil? %>
      <p>Number <span id="first_0"><%= @first_0 %></span> from number <span id="second_0"><%= @second_0 %></span> = <label id="answer_0"></label>%</p>
    <% end %>
  </div>

My new.js.erb

document.getElementById("answer_0").innerHTML = "<%= @result_0 %>"
document.getElementById("first_0").innerHTML = "<%= @first_0 %>"
document.getElementById("second_0").innerHTML = "<%= @second_0 %>"
Kirill Zhuravlov
  • 444
  • 9
  • 21

1 Answers1

1

It may be that the autocomplete pre-fills the values for you, try disabling it in your form:

<%= form_for :interest_calculator, url: { action: :new }, method: :get, autocomplete: false, remote: true do |f| %>

Another option will be to use POST method instead of GET.

First, remove method: get from form_for (default method is POST):

<%= form_for :interest_calculator, url: { action: :new }, remote: true do |f| %>

Second, update your routes:

post '/interest_calculator/new'
Gerry
  • 10,337
  • 3
  • 31
  • 40