0

I'm programming a web page for math tasks and want to set up a button which is generated dynamically, but my code generates '=" instead of " on the html page.

function generateButton(id){
    var b = "<button onclick='copyToClipboard(" + id + ", 'de');'>Copy to Clipboard </button>";
    $('#knopfdiv').append(b);
}

HTML

<div>
    <button onclick='generateButton(1);'>Show Button</button>
</div>
<div id="knopfdiv"></div>

So I expect the html line

<button onclick='copyToClipboard(1, 'de');'>Copy to Clipboard </button>

but I get

<button onclick="copyToClipboard(1, " de');'="">Copy to Clipboard </button>

and so that button does not work. What's wrong here?

Turnip
  • 35,836
  • 15
  • 89
  • 111
  • 3
    You have single quotes nested within single quotes. That is not valid syntax. You could replace with escaped double quotes `\"de\"` – Turnip Sep 12 '19 at 09:58
  • @melancia because both `'` and its nested `'` are inside `"`, there will not be a syntax error as it's a single string. – freedomn-m Sep 12 '19 at 10:12

1 Answers1

1

If you remove the variable (replace with hardcoded value), and take the HTML by itself, you get:

<button onclick='copyToClipboard(1, 'de');'>

It might not be obvious, but this has onclick='..'de'..' - ie a nested single quote within a single quote. jQuery is attempting to interpret this for you.

As your HTML is already wrapped in ", you can't just replace with , "de" but you can escape the " to \", giving:

<button onclick='copyToClipboard(1, \"de\");'>

applied to the javascript:

var b = "<button onclick='copyToClipboard(" + id + ", \"de\");'>Copy to Clipboard </button>";
freedomn-m
  • 27,664
  • 8
  • 35
  • 57