1

I have a link that when clicked should assign a rails variable to a JavaScript variable. The JavaScript is then used to calculate the price. I have the price calculated with a hard coded value at the moment.

in the html I need data-price to be var blankPrice in the js. Any help would be great.

$("a.shirt-color-link").on("click", function(){
  calculatePrice($(this));
})
 function calculatePrice(){

 	var blankPrice = obj.attr("data-price");


 	console.log(blankPrice)
 	var pricePerSide = 3;

 	var printedSides = 0;

 	if (frontCanvas) {
 		var frontCanvasJson = JSON.parse(frontCanvas);
		
		if (frontCanvasJson && frontCanvasJson.objects.length > 0)
			printedSides++;
 	}

 	if (backCanvas) {
		var backCanvasJson = JSON.parse(backCanvas);

	 	if (backCanvasJson && backCanvasJson.objects.length > 0)
	 		printedSides++;
 	}

 	var total = blankPrice + (pricePerSide * printedSides);
 	$('.base-price').text('$' + total);
 }
<a 
   tabindex="-1" 
   data-original-title="<%= shirt_color.color_name.titleize %>"
   class="shirt-color-link" 
   data-color="#<%= shirt_color.hex %>" 
   data-price="<%= product.base_price %>" 
   data-product-id="<%= product.id %>">
</a>

2 Answers 2

2

Where is the click handler for the link element?

You can do the following in jQuery: first add a click hander to the link:

$("a.shirt-color-link").on("click", function(){
   calculatePrice($(this));
})

Then in calculatePrice add argument obj and replace var blankPrice = 5; with:

var blankPrice = obj.attr("data-price");

obj refers to the clicked link and it's data-attributes.

Sign up to request clarification or add additional context in comments.

2 Comments

so i edited to your answer. Im just a bit unclear about the obj and how to assign it.
function calculatePrice(obj)
0
$('.shirt-color-link').attr("data-price", blankPrice);

EDIT - this is changing the "data-price" attribute to be whatever the value of the blankPrice variable is. You might want it the other way round, on reading again (it's a bit unclear), in which case do

var blankPrice = parseInt($('.shirt-color-link').attr("data-price"));

3 Comments

Don't forget the radix ;-)
What @Mouser means is that when using parseInt(), proper practice is to pass the second radix argument in to tell it what base to use in the conversion. I tend to not bother which is a bit naughty: some browsers (or other clients) might not convert it properly otherwise. see developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
You naughty boy ;-), like me you like to live dangerously. I try to include it nowadays, since I first read about it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.