I would like to pass a parameter (i.e. a string) to an Onclick function.
For the moment, I do this:
JavaScript
x
2
1
'<input type="button" onClick="gotoNode(' + result.name + ')" />'
2
with result.name for example equal to string “Add”.
When I click on this button, I have an error that says that “Add is not defined”. Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols “” in the string.
How can I fix this problem?
Advertisement
Answer
It looks like you’re building DOM elements from strings. You just need to add some quotes around result.name:
JavaScript
1
2
1
'<input type="button" onClick="gotoNode('' + result.name + '')" />'
2
You should really be doing this with proper DOM methods though.
JavaScript
1
8
1
var inputElement = document.createElement('input');
2
inputElement.type = "button"
3
inputElement.addEventListener('click', function(){
4
gotoNode(result.name);
5
});
6
7
•document.body.appendChild(inputElement);•
8
Just be aware that if this is a loop or something, result
will change before the event fires and you’d need to create an additional scope bubble to shadow the changing variable.