SupremeA
SupremeA

Reputation: 1621

Need to get data for coffeescript after input is put in

I am in a rails app and I need to collect the inputs for 3 fields but I need to collect them after they are input by the user. I am trying this in coffeescript but not sure if it is correct?

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

My html is as follows:

<%= 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" %>

[EDIT: I am actually getting the error from the 1st value in the calculation]

Here is my coffeescript and where the error is coming from...

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

I am still getting the error

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

So I know something is not right.

Upvotes: 0

Views: 316

Answers (3)

nosleepfilipe
nosleepfilipe

Reputation: 76

Try to do something like this.

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

passing the event so you can get the currentTarget and convert the val() to Number

Upvotes: 0

Kaushlendra Tomar
Kaushlendra Tomar

Reputation: 1440

You trying to get element by name, If you have already mentioned id on element try to get the element by getElementById I think this should work for you.

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

Upvotes: 1

Yosvel Quintero
Yosvel Quintero

Reputation: 19070

Try with jQuery .val()

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

Upvotes: 0

Related Questions