Thanks for posting the updated solution from Dave Lee. It didn't work for me
until I discovered something after several hours of trial and error. I'm posting my discovery here in case it's helpful to anyone else.
By the way, this post assumes the reader has basic familiarity with javascript. If you don't,
https://www.w3schools.com/js is a great site for picking up the basics.
As noted,
var MyVariableContent = document.getElementsByClassName("MyVariableSet.MyVariableName")[0].textContent does indeed return the Flare variable text. But it also contains a hidden newline character at the end of the variable. For many uses, this doesn't matter. But I was trying to use the variable to return a value from a JSON array of key/value pairs (language codes and corresponding language names). Because the variable didn't exactly match a key in the array, I kept getting an "undefined" error.
When I converted the javascript variable to a JSON string (using JSON.stringify()), I didn't get "en" as expected; instead, I got
en\n. Apparently, converting the variable to a JSON string exposed the hidden newline character.
So I used substr() to extract just the language code from the variable, and reassigned it to the same variable. Then I was able to use the variable to get the required value from the array.
Since it will probably be helpful to see the actual code in addition to the explanation above, here it is. I put the code below in a template page:
Code: Select all
<span class="hide Language.LangCode"><MadCap:variable name="Language.LangCode" /></span>
(Language is the name of my Flare variable set, and LangCode is the variable itself.)
And here's the javascript code:
Code: Select all
var langcode = document.getElementsByClassName("Language.LangCode")[0].textContent;
langcode = langcode.substr(0,2); //extracts just the language code so \n is no longer included.
The result was a variable that only contained the expected language code and worked for the array.
I tried using substr() to count backward in the variable and remove \n, but I couldn't get it to work. So if you use this solution, you'll need to adjust the second argument in substr() to be the length of the text you want to extract.
Hope that helps someone!
Kathryn