Darbininkai Broliai
Darbininkai Broliai

Reputation: 159

Javascript quote escape giving bugs

I need to print a button to a div that would pass a variable MyVar(string), or, to be precise, it's value, as a parameter to a function addfr(). The code:

 document.getElementById("somediv").innerHTML="<button onclick=\"addfr(\""+MyVar+"\")\">Add as friend</button>";

Instead of the expected

    <button onclick="addfr("MyVar")">Add as friend</button>"

I get:

    <button onclick="addfr(" MyVar")"="">

What is happening here? Any ideas how to fix this?

Edit: The final solution is, for those interested:

  <button onclick=\"addfr(&quot;"+MyVar+"&quot;)\">Add as friend</button>

Upvotes: 1

Views: 75

Answers (2)

Juan S&#225;nchez
Juan S&#225;nchez

Reputation: 990

You can use single quotes instead:

document.getElementById("somediv").innerHTML="<button onclick=\"addfr('"+MyVar+"')\">Add as friend</button>";

Upvotes: 0

antinescience
antinescience

Reputation: 2359

It needs to be HTML escaped. Try using &quot; in place of \".

Upvotes: 3

Related Questions