Reputation: 437
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>
Upvotes: 1
Views: 76
Reputation: 13304
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
.
Upvotes: 2
Reputation: 32933
$('.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"));
Upvotes: 0