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?

3
  • Did you look at the generated HTML? you have a mess in your generated javascript. Commented Sep 19, 2015 at 20:11
  • 1
    SendData(3323 ANDINFO < DATA > (info_user)) Yup, looks like an error to me. Commented Sep 19, 2015 at 20:14
  • Does this answer your question? Pass a string parameter in an onclick function Commented Jul 19, 2021 at 18:59

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This comments out my variables, mate. Are you sure the escapes are correct?
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.
But in this example you are not passing variables. You are passing one string that is hard coded
@Earthling, check the workaround and SO answer I linked. Hope that may help you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.