FabricioG
FabricioG

Reputation: 3320

Unable to get data attribute from button element via Jquery

I'm not able to get the data attribute from a button element.

<button
class="btn btn-solid navigate"
value="2"
data-productId={{$product->id}}
id="size-click"
>
Next
</button>

Then I attempt to get it like so:

  $("#size-click").click(() => {
    let width = $("#prod-width").val();
    let height = $("#prod-height").val();
    var prodId = $(this).data("productId");

    console.log('this is prodId');
    console.log(prodId);

    const data = {
      prodId: prodId,
      step: 'Size',
      width: width,
      height: height,
    }

    postDataEstimate(data);

  })

I'm also trying this:

var prodId = $(this).attr('data-productId');

Can you let me know what I'm missing?

Upvotes: 1

Views: 66

Answers (1)

Majed Badawi
Majed Badawi

Reputation: 28414

Since you're using an arrow-function, this does not refer to the button:

$("#size-click").click(function() {
  var prodId = $(this).attr("data-productId");
  console.log('this is prodId');
  console.log(prodId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button
  class="btn btn-solid navigate"
  value="2"
  data-productId="1"
  id="size-click"
>Next</button>

If you still want to use it, you can use the event passed to the function:

$("#size-click").click(e => {
  var prodId = $(e.currentTarget).attr("data-productId");
  console.log('this is prodId');
  console.log(prodId);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button
  class="btn btn-solid navigate"
  value="2"
  data-productId="1"
  id="size-click"
>Next</button>

Upvotes: 2

Related Questions