skip to Main Content

I’m using wordpress and woocommerce, and I want to add some scripts to run when a product variation is selected, with jQuery.

I have a set of “buttons” in html like this:

<div class="adsw-attribute-option">
  <span class="meta-item-text sku-set" data-value="s">S</span>
  <span class="meta-item-text sku-set" data-value="m">M</span>
  <span class="meta-item-text sku-set" data-value="l">L</span>
  <span class="meta-item-text sku-set" data-value="xl">XL</span>
  <span class="meta-item-text sku-set" data-value="xxl">XXL</span>
  <span class="meta-item-text sku-set" data-value="xxxl">XXXL</span>
</div>

I add click listeners with the following:

$(".adsw-attribute-option > .meta-item-text").on("click", () => {})

And inside the handler I need to read the data-value attribute of the “button” that was clicked. First I tried: $(this).attr("data-value"). This returned undefined. I’ve tried with .data instead of the attr function, with the same result.

It seems like there’s some issue with the usage of $(this), I couldn’t read any of its properties like html, or class.

I thought $(this) should refer to the object, that the event was called on, but it seems, this is not the case.

What am I missing here? Is there any other way to retrieve the value of “data-value” in this case?

3

Answers


  1. You should use the .attr function:

    $(".adsw-attribute-option > .meta-item-text").on("click", function () {
      $(this).attr('data-value');
    });
    

    It’s important you don’t use an arrow function because you can’t call this when using an arrow function.

    Login or Signup to reply.
  2. if you’re using an arrow function for the handler, try using the function keyword instead. the arrow function will have the same this value as its parent context, so it won’t give you access to the attribute you’re trying to read.

    $(".adsw-attribute-option > .meta-item-text").on("click", function(e) {
        console.log($(this).attr('data-value'));
    });
    
    Login or Signup to reply.
  3. $(".adsw-attribute-option > .meta-item-text").on("click", e => {
      console.log($(e.target).data('value'));
      console.log(e.target.dataset.value);
    });
    

    You can use an arrow function, if you use the event passed in.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search