Reputation: 625
I have this piece of code inside my Freemarker template:
<form>
<#list elements as product>
<input id="${product.buyLink}" type="checkbox" onClick="addToCart()" /><#if product.title??>${product.title}</#if> - <#if product.price??>${package.price}<#else>missing price</#if><br />
<script src="/assets/js/addToCart.js" type="text/javascript"></script>
</#list>
</form>
My addToCart.js looks like this:
function addToCart() {
if (document.getElementById("${product.buyLink}").checked == true) {
console.log("Product removed from cart.")
} else {
console.log("Product addded into cart.")
}
}
When I run this code, Chrome dev tools keep showing this error message:
Uncaught TypeError: Cannot read property 'checked' of null
Also I think it is need to say that my variable ${product.buyLink}
is a string that contains many backlashes - for example it can look like this: "db/45493/t/524s"
. I also tried to console.log("${package.buyLink}");
at the top of my JS script and it returned ${package.buyLink}
.
So, tt seems like my JS script doesn't know ${product.buyLink}
at all or thinks it is equal to null. Where exactly is an error and what am I doing wrong?
Upvotes: 0
Views: 775
Reputation: 6314
JavaScript runs on the client, FreeMarker runs on the server.
Here is an illustration:
As you can see there's the Internet separating your JavaScript code from ${product.buyLink}
which is something that's processed by FreeMarker on the server. You need to either move the code from addToCart.js inside the <script>
tag of your FreeMarker template or create a new template from addToCart.js and process the template before you return it to the browser.
Just to make sure everything is clear your goal is to process ${product.buyLink}
on the server the JavaScript that runs in your browser must have db/45493/t/524s
already in it, JavaScript runs in your browser and has no idea what ${product.buyLink}
is.
Upvotes: 1