I am trying to dynamically insert a link into the DOM. The link hyperlinks to another Javascript function that takes in a single argument.
Depending on the variable type of the argument (integer or string), the function either generates an error or behaves as expected.
Edit: added a CodePen demo here
function appendLink(userInput){
var functionLink = document.createElement("a");
functionLink.innerHTML = "Call Function";
functionLink.href = "javascript:func("+ userInput + ")"; //calling function + concatenating dynamic input
document.body.append(functionLink);
}
function func(arg){
alert(arg);
}
If arg
is a string (e.g.: userInput = 83we0
-- this is the exact argument in my code), I get Uncaught SyntaxError: Invalid or unexpected token
However, if arg
is numerical (e.g.: userInput = 62121
), then the program behaves as expected, alerting "62121" when the dynamically-appended link is pressed.