Выполнение расчета для модала с использованием coffeescript - PullRequest
0 голосов
/ 29 мая 2018

Я пытаюсь сделать так, чтобы пользователь мог ввести 3 числа, и когда они нажмут кнопку отправки, они увидят модальное с расчетами из этих 3 чисел в модальном.Я не уверен, как это сделать.У меня есть вычисления в моем контроллере.

class WelcomeController < ApplicationController

  def how_much
    @price = (params[:amount])
    @mortgage = (params[:high_rent])
    @rent = (params[:current_rent])

    if @price && @mortgage && @rent.present?
      @monthly_savings = @mortgage - @rent
      @savings_goal = @price*0.03
      @months_to_buy = (@savings_goal/@monthly_savings).to_i
      @total_savings = @monthly_savings * @months_to_buy
    else
      @months_to_buy = 24
      @total_savings = "great savings"
    end
    respond_to do |format|
        format.json { render json: {:months_to_buy => @months_to_buy, :total_savings => @total_savings}}
      end
    end

end

Моя форма выглядит следующим образом ...

      <%= form_tag( '/welcome/how_much', post: true, remote: true) do %>
       <h5 class="label">Estimated new home cost?</h5>
        <%= text_field_tag 'price', nil, placeholder: 'ex. 100,000', class: "form-control form-control-lg" %>

       <h5 class="label">Estimated payment for a new home?</h5>
        <%= text_field_tag 'mortgage', nil, placeholder: 'ex. 1,200', class: "form-control form-control-lg" %>

       <h5 class="label">Current Monthly Rent?</h5>
        <%= text_field_tag 'rent', nil, placeholder: 'ex. 800', class: "form-control form-control-lg" %>

       <button type="button" class="btn btn-success btn-lg" data-toggle="modal" data-target="#savingsModal">
      See how we help
    </button>

<!-- Modal for sign-up -->
<div class="modal" id="savings_modal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <h3 class="modal-title" id="savingsModalTitle">You could be ready to buy in <%= @months_to_buy %> months</h3>
      <h5 class="modal-title">and have <%= @total_savings %>* to put towards a down payment & ...</h5>
      <div class="modal-body">
        <h4>Sign-up Now to get started!</h4>
      </div>
    </div>
  </div>
</div>
<% end %>

Наконец, вот CoffeeScript, который я имею.Он также имеет расчеты, но я не уверен, что мне следует делать вычисления в CoffeeScript или в контроллере.Я понятия не имею, если я делаю это правильно, или я полностью выключен, пожалуйста, помогите !!!!

# Calculate Savings jQuery
price = document.getElementsByName('house_amount')[0].value
mortgage = document.getElementsByName('high_rent')[0].value
rent = document.getElementsByName('current_rent')[0].value
MonthlySavings: (mortgage, rent) ->
 if mortgage? && rent?
   parseFloat(mortgage) - parseFloat(rent)
SavingsGoal: (price) ->
 if price?
   parseFloat(price) * 0.03
MonthsToBuy: (Savings_goal,MonthlySavings) ->
 if SavingsGoal? && MonthlySavings?
   parseFloat(SavingsGoal)/parseFloat(MonthlySavings)
TotalSavings: (MonthlySavings,MonthsToBuy) ->
 if MonthlySavings? && MonthsToBuy?
   parseFloat(MonthlySavings) * parseFloat(MonthsToBuy)

1 Ответ

0 голосов
/ 29 мая 2018
class Calculation
  constructor (@price, @mortgage, @rent) -> 
  monthly_savings -> @mortgage - @rent
  savings_goal -> @price * 0.03
  months -> Math.ceil @savings_goal / @monthly_savings
  savings -> monthly_savings * months

И создать экземпляр расчета:

price = document.getElementsByName('house_amount')[0].value
mortgage = document.getElementsByName('high_rent')[0].value
rent = document.getElementsByName('current_rent')[0].value
instance = new Calculation(price, mortgage, rent)

Затем отобразить его где-нибудь:

document.getElementById('total_savings').value = instance.savings();
...