Pass a string parameter in an onclick function

It looks like you’re building DOM elements from strings. You just need to add some quotes around result.name:

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

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

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

​document.body.appendChild(inputElement);​

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.

Leave a Comment