stackato stackato - 1 month ago 12
HTML Question

JavaScript -- Unable to pass object to onclick method

I have an image and when its clicked I am trying to pass an object to the onclick method but I get an error:

missing ) after argument list


the debugger console is showing the error on line 1, the same line as the HTML doctype declaration.

BUT, when I pass a string, everything works fine and the method is executed.

Can someone please tell me what I am missing here?

var item = {test:"blah"};// throws error
var emptyString= "";//works fine
str = str + '&nbsp;&nbsp;<img alt="" data-qtip="Submit Report" height="14px" width="14px" src="'+img+'" style="cursor:pointer" onclick="submitReport('+item+')"/>';


If I pass in emptyString, everything works fine.

thanks!

Answer

You should stringify object using JSON.stringify function:

str = str + '&nbsp;&nbsp;<img alt="" data-qtip="Submit Report" height="14px" width="14px" src="'+img+'" style="cursor:pointer" onclick="submitReport('+JSON.stringify(item)+')"/>';
Comments