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.
Open the Node. js command prompt. Browse through the path where you have saved the file and compile it using the -c option of the coffee command of the coffee command-line utility as shown below. On executing the above command, the CoffeeScript compiler compiles the given file (sample.
Short answer: No. CoffeeScript generates javascript, so its maximum possible speed equals to the speed of javascript.
If you are looking to implement coffee script in html, take a look at this. You simple need to add a <script type="text/coffeescript" src="app. coffee"></script> to execute coffee script code in an HTML file.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With