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.
Your
selection = 1inside yourifstatements is (still) an assignment in CoffeeScript, you need to use==for comparison. Try this:Also,
==is converted to===so you’ll want to compare against strings unless you want to “cast” your value to a number usingselection = +select.val()(thanks to Trevor Burnham for this casting trick) orparseInt(select.val(), 10).