输入后需要获取coffeescript的数据

时间:2018-05-30 05:18:14

标签: javascript html ruby-on-rails coffeescript

我在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)

所以我知道有些事情是对的。

3 个答案:

答案 0 :(得分:1)

你试图按名称获取元素,如果你已经在元素上提到过id尝试通过getElementById获取元素,我认为这应该适合你。

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

答案 1 :(得分:0)

尝试使用jQuery .val()

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

答案 2 :(得分:0)

尝试做这样的事情。

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

传递事件,以便获取currentTarget并将val()转换为Number