user1906288
user1906288

Reputation: 11

Global var in function with arguments

I have:

HTML:

<a href="" class="add-to-cart-button" onClick="javascript:addToCart([@id]);">Add to cart</a>

and Javascript:

var pid;
function addToCart(id){
pid = id;
}
alert(pid);

It return 'unidentified' How can I assign value from addToCart(id) to pid? thanks!

Upvotes: 1

Views: 112

Answers (2)

JAAulde
JAAulde

Reputation: 19560

Your JavaScript is executed during pageload to

  1. declare a variable named pid (declare only, no value defined)
  2. declare and define a function named addToCart (declare and define, not execute...)
  3. alert the declared pid variable (which has yet to be defined as any value)

Also, during pageload, your markup is parsed, and the JavaScript engine defines (but does not execute) a click handling function which will call addToCart() when the element is clicked.

It is when the element is clicked that addToCart will be run, giving pid a definition, and this is all after the alert took place during page load.

Alerting within your addToCart function after setting pid, however, will show you the proper value.

Also, see comments and answers regarding @id.

As an added note, the javascript: pseudo-protocol you're using at the start of your onclickattribute is not appropriate in that attr, and has been deprecated where it used to be appropriate (such as in an href attr). You should remove it and cease all use of it.

Upvotes: 1

Zoltan Toth
Zoltan Toth

Reputation: 47667

Your pid is undefined when you're loading the page. To show the actual value you have to put the alert inside the function:

var pid;
function addToCart(id){
    pid = id;
    alert(pid);
}

DEMO

Upvotes: 3

Related Questions