Assign a particular field of each card to a variable using JavaScript

From the back template of my cards, am trying to assign a field to a variable using;

<script>
let Variable={{field}};
</script>

However this happens only once at the start of my cards. It works only for the first card and that’s it, the variable maintains that value assigned to it in the first instance. Apparently the variable is not getting assigned at the start of each card.

Some suggestion were that I should have the variable assignment statement in a function, others were to use var, instead of let in my assignment but none of these seems to be working out. How do I work around this? Any suggestion will be much appreciated. Thanks already.

I am a beginner.
I don’t know the principle.
I tried to use:

<div id="front">{{Field}}</div>
<div id="now"></div>
document.getElementById("now").innerHTML = document.getElementById("front").innerHTML
var virable = document.getElementById("front").innerHTML

It takes effect on multiple cards.
Although let confuses me too and maybe var can avoid the problem, you can try the above method.
:yum:

1 Like

Surround it with the backtick characters:

<script>
let Variable = `{{field}}`;
</script>

Anki simply replaces the double-curly-braced text with the contents of the respective fields, so think of it as such. If the field contains someword, the code passed to JS will be let Variable = someword;, so JS will interpret the right-hand side as a name for a variable, which is likely undeclared and will break things. But if it’s let Variable = `someword`; it will be treated as a string, so everything should be fine.

Of course, you have to make sure the {{field}} itself doesn’t contain any ` inside, which is why ` is probably a better choice for marking the contents of a string since ' are often encountered in English shortenings such as don't, and " is likely to be present if the {{field}} has html formatting.

Thanks for the response

I actually had a bunch of other stuffs in that script tag ()… but upon isolating the assignments into their own tags, it seems to work just fine. Thanks for the response

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.