March 10, 2012

pass string parameter in an onclick function

Question by Jaspack

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

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

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 definied. 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?

Answer by david

It’s 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.

Answer by Starx

I am guessing, you are creating a button using JavaScript itself. So, the error in your code is that, it will render in this form

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

At this current state, add will be considered as an identifier like variables or function calls. You should escape the value like this

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!