输入后需要为coffeescript获取数据

Need to get data for coffeescript after input is put in

我在 rails 应用程序中,我需要收集 3 个字段的输入,但我需要在用户输入它们后收集它们。我在 coffeescript 中尝试这个但不确定它是否正确?

$("#mortgage").change ->
  mortgage = document.getElementsByName('mortgage')[0].value
$("#price").change ->
  price = document.getElementsByName('price')[0].value
$("#rent").change ->
  rent = document.getElementsByName('rent')[0].value

我的html如下:

<%= text_field_tag :price, nil, placeholder: "ex. 100,000", class: "form-control form-control-lg", id: "price" %>

<%= text_field_tag :mortgage, nil, placeholder: "ex. 1,200", class: "form-control form-control-lg", id: "mortgage" %>

<%= text_field_tag :rent, nil, placeholder: "ex. 800", class: "form-control form-control-lg", id: "rent" %>

[编辑:我实际上是从计算中的第一个值得到错误]

这是我的 coffeescript 以及错误的来源...

# Calculate Savings
$('#mortgage').change ->
  mortgage = $(this).val()
$('#price').change ->
   price = $(this).val()
$('#rent').change ->
   rent = $(this).val()
instance = new Calculation(price, mortgage, rent)<!---ERROR IS HERE FOR PRICE--->

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

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

我仍然遇到错误

Uncaught ReferenceError: price is not defined I assume that is because it is first)

所以我知道有些地方不对。

您尝试通过名称获取元素,如果您已经提到元素的 id,请尝试通过 getElementById 获取元素,我认为这应该适合您。

$('#mortgage').change ->
  mortgage = $(this).val()
$("#price").change ->
   price = $(this).val()
$("#rent").change ->
   rent = $(this).val()

试试 jQuery .val()

$('#mortgage').change ->
  mortgage = $(this).val()

尝试做这样的事情。

$('#mortgage').change (event) ->
  mortgage = Number $(event.currentTarget).val()

传递事件以便您可以获得 currentTarget 并将 val() 转换为 Number