1

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?

5
  • Where are you trying to get prodId? Commented Mar 9, 2021 at 18:44
  • In a separate js file. @MajedBadawi Commented Mar 9, 2021 at 20:19
  • @MajedBadawi I just updated the code to show where I'm trying to get it. Commented Mar 9, 2021 at 20:22
  • your are missing quotes data-productId={{$product->id}} Your markup breaks after that Commented Mar 9, 2021 at 20:24
  • This doesn't work either: data-productId="{{$product->id}}". @ikiK Commented Mar 9, 2021 at 20:29

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.