Alex Rivera | Logout

Why won't my CoffeeScript if/else statement work?

Asked 2011-11-11T06:00:01.823
15

I've been trying to update a total price when someone changes the select option. Here is the select element I'm using:

<select id="payment_talks_purchased" name="payment[talks_purchased]">
  <option value="1">One</option>
  <option value="2">Three</option>
</select>

This is the jQuery I'm using:

jQuery(document).ready(function() {
  var price = $(".total-price span.price")
  var save = $(".savings")
  $("#payment_talks_purchased").change(function() {
    var selection = $("#payment_talks_purchased").val()
    if (selection == 2) {
      price.html("$12");
      save.css("visibility", "visible");
    } else if (selection == 1) {
      price.html("$5");
      save.css("visibility", "hidden");
    }
  });  
});

It works perfectly. It changes the price to $12 and shows the discount message. If I change the select option back to One/1, it changes the text back to $5 and removes the discount message.

I converted this to CoffeeScript but it only works when I make the first change. The price is updated. However, when I try to change it back to option 1, it doesn't update.

jQuery ->
  price = $(".total-price span.price")
  save = $(".savings")
  select = $("#payment_talks_purchased")
  select.change ->
    selection = select.val()
    if selection = 2
      price.html "$12"
      return save.css "visibility", "visible"
    else if selection = 1
      price.html "$5"
      return save.css "visibility", "hidden"

I've been working on this for hours and am at my wits end. Any help would be greatly appreciated.

Edit
Report

1 Answer

26

Your selection = 1 inside your if statements is (still) an assignment in CoffeeScript, you need to use == for comparison. Try this:

jQuery ->
  price = $(".total-price span.price")
  save = $(".savings")
  select = $("#payment_talks_purchased")
  select.change ->
    selection = select.val()
    if selection == '2'
      price.html "$12"
      return save.css "visibility", "visible"
    else if selection == '1'
      price.html "$5"
      return save.css "visibility", "hidden"

Also, == is converted to === so you'll want to compare against strings unless you want to "cast" your value to a number using selection = +select.val() (thanks to Trevor Burnham for this casting trick) or parseInt(select.val(), 10).

answered 2011-11-11T06:06:44.103

Your Answer