onclick="doSomething([object Object])" Uncaught SyntaxError: Unexpected identifier
Asked Answered
P

6

8

var params = {a:1,b:2}; var str = '<a href="#" onclick="doSomething('+params+')">aaaa</a>'; document.write(str);

when I click the <a> on the page,it throws "Uncaught SyntaxError: Unexpected identifier".I can't understand.

Primacy answered 1/8, 2012 at 5:50 Comment(0)
U
13

The reason is that when you use string concatenation, params is casted to string, as result you get something like [object Object] in parenthesis.

You should better put params as var params = '{a:1,b:2}';.

Upd.
As suggested in comments, another viable approach is using JSON.stringify:

var params = {a:1,b:2};
var str = '<a href="#" onclick="doSomething('
    + JSON.stringify(params)
    + ')">aaaa</a>';
document.write(str);

Please, pay attention that JSON.stringify may not be supported by older browsers and you'll need to include additional libraries to make them work.

Uriel answered 1/8, 2012 at 5:52 Comment(2)
I would add to this that if you cannot hard code the object like is shown in the example and actually need to convert an object to string, you can use JSON.stringify(params) to ensure the correct format.Inger
note that, according to escape.alf.nu, %22 gets parsed to ", so passing this value to href instead of onclick will lead to XSS vulnerabilities.Exurbanite
F
1

[object Object] is the string representation of any JavaScript object. In your scenario you have params concatenated with a string, which will cast any variable type to a string.

Filmdom answered 1/8, 2012 at 5:52 Comment(0)
P
0

The in your case str looks like this: <a href="#" onclick="doSomething([object Object])">aaaa</a>

As you can see, that is not what you want.

Pearlstein answered 1/8, 2012 at 5:55 Comment(0)
I
0

The answer by Li0liQ is quite Ok. When you clicking on that link you can find doSomething[object Object]

This is only object required .You are not writing the params into document. Casting Problem.

Impossibly answered 1/8, 2012 at 6:21 Comment(0)
N
0

Ran into same issue. Reason for the issue: params is converted to string 'object Object' when html is rendered.

The problem can be sorted out in two ways:

Approach 1: add a click handler to the js code. Refer add click handler

Approach 2: Say I want to pass a JSON object named 'params' to the onclick function. As I need a very few attributes of the 'params' object, instead of adding a new handler as in 1st approach, I would rather just pass those specific parameters as below:

'<a href="#" onclick="doSomething(\'' + params['attribute1'] + '\'\, \'' +params['attribute2'] + '\'\)">aaa</a>'
Nunhood answered 19/5, 2020 at 16:27 Comment(0)
M
0

<button class="btn btn-primary" onclick='setInputForUpdate(${JSON.stringify(data)})' data-bs-toggle="modal"

Maggi answered 1/11, 2023 at 5:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.