Reputation: 11
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
Reputation: 19560
Your JavaScript is executed during pageload to
pid
(declare only, no value defined)addToCart
(declare and define, not execute...)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 onclick
attribute 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
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);
}
Upvotes: 3