Reputation: 107
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.
Upvotes: 1
Views: 27
Reputation: 370689
Considering
func("+ userInput + ")";
Numbers work because the produced syntax will be something like
func(123)
Non-numbers won't, because the produced syntax will be something like
func(83we0)
Strings require delimiters.
While you could fix this by conditionally adding delimiters and escaping them inside the argument, it would be far better to avoid inline handlers entirely, and use addEventListener
instead, that way you don't have to worry about silly and tedious escaping issues:
functionLink.addEventListener('click', () => func(userInput));
Do that instead of assigning javascript:
to the href
.
Upvotes: 1