user1403848
user1403848

Reputation: 103

Passing a variable using an onclick event to a function for a dynamically created button

Please find the code below. When I'm trying to pass the variable tmp_lnk from the onclick event to the function it throws up an error that tmp_lnk is not defined. How do I pass the variable to the function?

if(fig_name[1]==img_name)
{
var tmp_lnk = "Supplementary Notes for Images/"+"6H-"+img_name/img_name+".pdf"
$("#notes1").append('<div><a onclick="On_Click(tmp_lnk)" id="closebutton">NOTES</a></div>')
break;
}}

function On_Click(tmp_link)
{
    window.open("tmp_lnk");
}

}

Upvotes: 0

Views: 1388

Answers (3)

Soulbe
Soulbe

Reputation: 554

$("#notes1").append('<div><a onclick="On_Click(' + tmp_lnk+ ')" id="closebutton">NOTES</a></div>')

And

function On_Click(tmp_lnk)
{
    window.open(tmp_lnk);
}

Upvotes: 1

NullPoiиteя
NullPoiиteя

Reputation: 57312

because you declare the tmp_lnk in if make it global or declare out side of the if

var tmp_lnk
if(fig_name[1]==img_name)
{
tmp_lnk = "Supplementary Notes for Images/"+"6H-"+img_name/img_name+".pdf"
$("#notes1").append('<div><a onclick="On_Click(tmp_lnk)" id="closebutton">NOTES</a></div>')
break;
}}

function On_Click(tmp_link)
{
    window.open("tmp_lnk");
}
}

Good Read

JavaScript Variable Scope

Upvotes: 0

Adriano Carneiro
Adriano Carneiro

Reputation: 58595

Alternatively, how about this:

$("#notes1").append('<div><a onclick="On_Click('+tmp_lnk+')" id="closebutton">NOTES</a></div>')

That would make the variable content written on the method call, solving your issue.

Upvotes: 0

Related Questions