Skip to content Skip to sidebar Skip to footer

How Can I Pass A Variable Through An Onclick Event When Javascript Is Creating The Html?

My javascript creates a line of html. That html has an onclick event call to openSingle(). I need to pass a variable into that function. onclick='openSingle('+findID+')' When I che

Solution 1:

You can escape quotes with a backslash like so

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';

and as other comments suggested you should ideally avoid inline Javascript


Solution 2:

Escape the single quotes, like this:

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\')"/>';

Solution 3:

try adding \' will fix the problem

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';

Solution 4:

Here is the answer: with escaping character \ for ' character

var iconImage = '<img src="../../resources/images/annotation-icon.png" style="float:left; margin-left:20px; margin-right:0px;"onclick="openSingle(\''+findID+'\;)"/>';

Also try concating &lsquo;and&rsquo;


Solution 5:

One thing you could try doing is attach the onclick after you create the DOM node. This lets you be as flexible as you want and avoids having to eval strings and other things like that.

var domnode = /* get the image tag */
domnode.onclick = function(){ openSingle(findId) }

Post a Comment for "How Can I Pass A Variable Through An Onclick Event When Javascript Is Creating The Html?"