2

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?

Jay
  • 4,873
  • 7
  • 72
  • 137
  • Did you look at the generated HTML? you have a mess in your generated javascript. – Amit Sep 19 '15 at 20:11
  • 1
    `SendData(3323 ANDINFO < DATA > (info_user))` Yup, looks like an error to me. – Farzher Sep 19 '15 at 20:14
  • Does this answer your question? [Pass a string parameter in an onclick function](https://stackoverflow.com/questions/9643311/pass-a-string-parameter-in-an-onclick-function) – Heretic Monkey Jul 19 '21 at 18:59

1 Answers1

1

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.

Community
  • 1
  • 1
rajuGT
  • 6,224
  • 2
  • 26
  • 44
  • This comments out my variables, mate. Are you sure the escapes are correct? – Jay Sep 19 '15 at 20:18
  • I've not used escapes. but your earlier function would be set like `"SendData(3323 ANDINFO < DATA > (info_user))` but what I made is `"SendData('3323 ANDINFO < DATA > (info_user)')`. Passed value must be either string, object reference, number or boolean. But the earlier 1 is neither. bcoz there wasnt '' quotes. Just check once and let me know, if issue still persists. – rajuGT Sep 19 '15 at 20:23
  • 1
    But in this example you are not passing variables. You are passing one string that is hard coded – Jay Sep 19 '15 at 20:24
  • @Earthling, check the workaround and SO answer I linked. Hope that may help you. – rajuGT Sep 19 '15 at 20:43