Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
94
rated 0 times [  99] [ 5]  / answers: 1 / hits: 33403  / 12 Years ago, sun, may 6, 2012, 12:00:00

It's a very simple question but I couldn't figure it out. I'm trying to pass parameters to a Javascript function which is invoked when a hyper link is clicked.



It works just fine when the parameters are number but doesn't work when one of them is of type string. I even tried to escape them but unfortunately to no avail.



The following is a very simple code.



function temp(a, b)
{
alert(a+ +b);
}

<a href=javascript:void(0); onclick=temp(x, 2);>Click</a>


It doesn't work complaining x is undefined x is here onclick=temp(x, 2);. When I modify the function something like this temp(1,2);, it works and alerts as specified.



What might be the reason? What is the solution?


More From » javascript

 Answers
117

you should avoid passing an undefined variable... x is only a variable as a string starts and end with double or single quotes



function temp(a, b) {
alert(a+ +b);
}

<a href=javascript:void(0); onclick=temp('x', 2);>Click</a>


I also created a fiddle to show it works



EDIT: this revision of the fiddle shows that you can also switch the quotes used in the markup... if you are used to double quotes for JS strings fiddle revision 1


[#85762] Friday, May 4, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coby

Total Points: 27
Total Questions: 102
Total Answers: 97

Location: Honduras
Member since Wed, Jul 14, 2021
3 Years ago
coby questions
;