Paulo Janeiro
Paulo Janeiro

Reputation: 3211

jQuery `this` scope issue

I have a global function defined in one place:

function addToCart (){
    var prodText = $(this).parent().siblings(".item1").text();
    $("#"+prodId+"shopC").children(".item1").text(prodText);
    alert(prodText);
}

Then, I want to call it inside a HTML element with an inline onClick event: onClick='addToCart()'

It is not working, but it works if I put the function code directly inside the onClick event, so that must be a this scope issue. There are many questions/explanations about this scope but I must confess I miss a simple straight answer for this specific case (I tried to use "use strict" with success either). How to make this work?

Upvotes: 2

Views: 74

Answers (4)

Oss
Oss

Reputation: 4322

this object in your function does not point to the object where you added the onClick function to. It rather points to the window object.

You need to pass this as a param to your function.

function addToCart (trigger) { // Code goes here }

and call addToCart(this) in your onClick.

Learn more about this in javascript here.

Upvotes: 0

DK3
DK3

Reputation: 403

you have to pass this keyword where you inline calling the addToCart function then you can capture that element

onClick='addToCart(this)'

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67187

Basically this inside a plain function will point to window. you have to pass the this context to the inline handler onClick='addToCart(this)'. Receive it and use it inside of event handler like below.

function addToCart (_this){
  var prodText = $(_this).parent().siblings(".item1").text();

Upvotes: 1

Satpal
Satpal

Reputation: 133403

As per current implementation this doesn't refers to the element which invoked the function. It refers to window object.

You need to pass the current element context i.e. this to the function as

onClick='addToCart(this)'

and modify the function to accept element as parameter.

function addToCart (elem){
    var prodText = $(elem).parent().siblings(".item1").text();
    $("#"+prodId+"shopC").children(".item1").text(prodText);
    alert(prodText);
}

Upvotes: 4

Related Questions