0

I am trying to return a button in some function on UI and get a wierd error. Can someone please help.

var div = "<button onclick='javascript:displayDetails('+value1+','+value2+');'>View</button>"

Error i get is:

missing ) after argument list.

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
fiddle
  • 1,095
  • 5
  • 18
  • 33

3 Answers3

1
 onclick="javascript:displayDetails('+value1+','+value2+');"

Not

 onclick='javascript:displayDetails('+value1+','+value2+');'

Use `` which supports multiple lines instead of '' and to avoid nested "":

const div = `
   <button onclick="javascript:displayDetails('+value1+','+value2+');">
       View
   </button>`;

Not

const div = "<button onclick='javascript:displayDetails('+value1+','+value2+');'>View</button>"

Then you will not need to espace

Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
0

You should escape:

var div = "<button onclick=\"javascript:displayDetails('+value1+','+value2+');\">View</button>"
pierlauro
  • 176
  • 4
0

The latest version of JavaScript (ES2015, formerly/also known as ES6) now supports "template strings" that can help avoid just this kind of quoting/escaping nightmare. Use the "backtick quote" (aka grave accent) around the string to signal a template string, and a template syntax of ${value} for each value you want "interpolated" (included) into the string:

var div = `<button onclick="javascript:displayDetails(${value1},${value2});">View</button>`;

In general, it's best to choose a standard for which quote marks you're going to use when. Many modern JavaScript style guides prefer single quotes (') for normal strings, and double quotes (") for surrounding HTML (or XML) attributes. Now having a third quotation mechanism means you don't have to backslash-escape quote marks so often--nice, because escaping is annoying, error-prone, and anti-clarity.

Jonathan Eunice
  • 21,653
  • 6
  • 75
  • 77