Find the best answer to your technical question,
help others answer theirs

If you are going to use a passage of Lorem Ipsum, you need to be sure there
isn't anything embarrassing hidden in the middle of text.

  • Anybody can ask a question
  • Anybody can answer
  • The best answers are voted up and rise to the top
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?

Edit
avatar
Arden Smith
224,110 16 93 136
asked 6 hours ago

Leave a Comment

[named hyperlinks] (https://example.com)
**bold**
_italic_

1 Answer

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>
Edit
avatar
Majed Badawi
15.5k 3 10 26
answered 8 hours ago

Leave a Comment

[named hyperlinks] (https://example.com)
**bold**
_italic_

Your Answer

Drop files here or click to upload.