Jay
Jay

Reputation: 5084

Javascript Passing variable to an onclick doesn't work

I'm trying to pass variables to another function via HTML generation using Javascript but it doesn't get through. Here's my code:

var wer_people_btn1 = document.createElement("span");
wer_people_btn1.setAttribute('onclick', 'SendData(' + user.ID + " ANDINFO " + susData + ')');

function SendData(reply) {
}

user.ID contains "3323"

susData contains "< DATA > (info_user)"

The error I get:

Uncaught SyntaxError: missing ) after argument list

I think the <> brackets are causing trouble here. How do I pass these as a string to my function?

Upvotes: 2

Views: 548

Answers (1)

rajuGT
rajuGT

Reputation: 6414

Because what ever you send, that data has to be a string. So string must be in quotes ' or " but it should not conflict. so make use of Javascript's both single and double quotes or try with only one by making use of escape character \'

wer_people_btn1.setAttribute('onclick', "SendData('" + user.ID + " ANDINFO " + susData + "')");

As mentioned in the comment, only event and element(this) can be passed.

Better workaround: The above will create a single string input for SendData, but you want to receive as separate parameters, then the following one works "SendData(" + user.ID + ",'" + susData + "')"); where the function prototype of SendData is SendData(userId, susData) //no quotes for user.ID since it is a number

If you need to pass custom objects, then look at this SO 1st answer, those are the only possible ways I know.

Upvotes: 1

Related Questions