Reputation: 901
I am constructing an HTML snippet with a JavaScript function that injects into a div.
Can't figure out how to do the quote / double quote wrapping for a passed variable dynamically.
var vLC = "zh-CN"
var vHtml = "<input type='radio' id='rbtn1' onclick='renderList(" + vLC + ");' />";
This code renders: onclick="renderList(zh-CN);"
I need it to render: onclick="renderList('zh-CN');"
Any geniuses out there that know the Code?
Upvotes: 0
Views: 976
Reputation: 901
www.jsbin.com to the rescue! - Thanks to Remy Sharp @rem :-D
Solution was to use a variable for the onclick action.
var vLanguageCode = "us-EN";
var vOnclick = 'renderList("' + vLanguageCode + '")';
vHtml = "<input type='radio' id='rbtn1' onclick=" + vOnclick + " />";
Simplify, simplify...
Upvotes: 0
Reputation: 2464
var vLC = "zh-CN"
var vHtml = "<input type=\"radio\" id=\"rbtn1\" onclick=\"renderList('" + vLC + "');\" />";
Upvotes: 0
Reputation: 943220
Don't modify your document by mashing strings together. It is more pain to maintain then it is worth.
var element = document.createElement('input');
element.type = "radio";
element.id = "rbtn1";
element.addEventListener('click', function () {
renderList(vLC);
});
This is a general rule. If you are dealing with one language (programming, templating, data serialisation, whatever) inside another you meet pain. When you add another layer (JS inside HTML inside JS here) you get horrible pain.
Always either use an API to build the document, or build each layer in turn and add it to the next after running it through an escaping routine.
Upvotes: 2