我正在使用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" %>


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

这是我的coffescript,错误是从哪里来的...

# 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()

关于javascript - 输入后需要获取coffeescript的数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/50596831/

10-12 12:21
查看更多