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
You should use the .attr function:
It’s important you don’t use an arrow function because you can’t call this when using an arrow function.
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.You can use an arrow function, if you use the event passed in.