Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following Problem:

I'm trying to build a simple string like that:

for(var x in classicde) {
    specificWines += "<li><a onClick='displayWine(" + "'GV'" + ")'>" + classicde[x] + "</a></li>";
}

Then I insert this string in the DOM structure with:

var list = document.getElementById("leftmenu-list");
list.innerHTML = specificWines;

The result is the following(something like that i have shortened it):

<ul id="leftmenu-list">
    <li><a onclick="displayWine(" gv')'>Classic1</a></li>
</ul>

So there is a problem within the onclick event and i am not able to find the issue.

share|improve this question
    
Why do you need any concatenation between your onClick's parenthesis and "gv"? –  thomas 39 mins ago

1 Answer 1

up vote 0 down vote accepted

Your quotes are wrong around 'displayWine(" + "'GV'" + ")' it should be 'displayWine(" + "\"GV\"" + ")' so the single quotes contains double quotes and do not break the attribute on render. \ is used to escape the quote so it doesn't break the JS code.

for(var x in classicde) {
    specificWines += "<li><a onClick='displayWine(" + "\"GV\"" + ")'>" + classicde[x] + "</a></li>";
}

Otherwise as you see you end up with the single quote breaking the attribute. If you pass a string inside a string you need to make sure you use different quotes.

This should now render as

<li><a onclick='displayWine("gv")'>Classic1</a></li>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.