thevan
thevan

Reputation: 10364

How to pass argument programmatically in JavaScript?

This is my code,

var baseurl = "https://localhost:8888/files/";

var mydiv = document.getElementById("myDiv"); 
var aTag = document.createElement('a');
aTag.setAttribute('href',"#");
aTag.setAttribute('onclick',"getFolderList(" + baseurl + ")"); 
aTag.innerHTML = "Home /";
mydiv.appendChild(aTag);

Here, getFolderList is the JavaScript function which accepts one parameter. I used the above code, but it does not call the function. How to pass the "baseurl" value to the getFolderList function?

Upvotes: 0

Views: 440

Answers (1)

CodingIntrigue
CodingIntrigue

Reputation: 78605

You forgot to include quotes:

aTag.setAttribute('onclick',"getFolderList('" + baseurl + "')");
                                           ^               ^

The way you have written it, the engine will treat https://localhost:8888/files/ as the variable name, which of course would cause a syntax error.

Finally, you should avoid writing code like this inside HTML attributes - it could lead to script injection attacks if baseurl comes from an external source. Use the event listener syntax instead:

aTag.addEventListener("click", function() {
    getFolderList(baseurl);
});

Upvotes: 3

Related Questions