Consec Consec - 5 months ago 29x
Javascript Question

pass string parameter in an onclick function

I would like to pass a parameter (i.e. a string) to an Onclick function. For the moment, I do this:

'<input type="button" onClick="gotoNode(' + + ')" />'

with 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 functioncall works perfect with a numeric parameter, I assume that it has something to do with the symbols "" in the string.
Did anyone had this problem before?


It's looks like you're building dom elements from strings. You just need to add some quotes around

'<input type="button" onClick="gotoNode(\'' + + '\')" />'

You should really be doing this with proper DOM methods though.

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){


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.