Jump to content

Inserting JS function with String parameter into HTML


dexter

Recommended Posts

I want to insert an HTML tag with an onclick event that calls a function with a String parameter.This is what I've tried thus far (Note: This is merely snippets. Everything not related to the question works, eg. ids[j] is a valid String and htmlCode does get inserted into the HTML code of the page):

tmp = "'"+ids[j]+"'";htmlCode+='<span onclick="test(' + tmp + '"></span>';

and (Note: ignore the space in & #34;):

tmp = '& #34;'+ids[j]+'& #34;';htmlCode+='<span onclick="test(' + tmp + '"></span>';

Neither worked, what can I do?

Link to comment
Share on other sites

You can escape the quotes.

tmp = ids[j];htmlCode+="<span onclick=\"test(' + tmp + ')\"></span>";

Link to comment
Share on other sites

Make sure have the closing parenthesis in your argument list with the test() function. Synook included it, but wanted to make sure you are aware that it is missing in your code.

Link to comment
Share on other sites

Thnx ScottR. My first code segment worked when I added the closing parameters. For anyone who wants to see the working example, here it is:

tmp = "'"+ids[j]+"'";htmlCode+='<span onclick="test(' + tmp + ')">';

That means, if u want to insert a JS function with a String parameter into HTML, the trick is something like this (where u include htmlCode into u'r HTML by using somtehing like innerHTML):

tmp = "'"+param+"'";htmlCode = '<span onclick="test(' + tmp + ')"><p>BlaBlaBla</p></span>';

(Note: I don't know why, but 4 some reason Synook's code didn't work. It also didn't work when I edited it as follows:

htmlCode+="<span onclick=\"test('" + tmp + "')\"></span>";

).

Link to comment
Share on other sites

Oops I see the error in my snippet but

htmlCode+="<span onclick=\"test('" + tmp + "')\"></span>";

works fine (as long as tmp is defined).

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...