2

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?

2
  • you x is a variable assignment... use 'x' to pass it as string Commented May 6, 2012 at 12:57
  • That I also tried but unfortunately no luck. Commented May 6, 2012 at 12:58

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

3 Comments

I had to do something like this to make it work in my actual application in JSP onclick=\"selectOrderStatus('"+od_status+"', "+order_id+";);\". Even this one onclick='selectOrderStatus('"+od_status+"', "+order_id+");' enclosed within single quotes doesn't work.
Not even this one were working onclick='selectOrderStatus('\"+od_status+\"', \"+order_id+\");'. Therefore, I needed to post the question here. Thanks.
a you should mention in the question that the code is generated via PHP and a small piece of this php code would have also helped :)
3
<a href="javascript:void(0);" onclick="temp('x', 2);">Click</a>

Demo

With your code, you treat x as it was a variable, while it wasn't decalred, surrond it with quotes.


If you want to use the x variable, declare it about the <a>:

<script>
    var x ="foo";

    function temp(a, b) {
        alert(a + "   " + b);
    }​
</script>

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.