最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I get data attribute value of clicked button? - Stack Overflow

programmeradmin5浏览0评论

I want to get data attribute value of clicked button. I need to use it When I submit an ajax form. How can I get that ?

My button (There are as many buttons as the number of products)

<input value="Add To Cart" type="button" class="btn btn-success btn-sm btn-block add-to-card-button" data-id="{{$product->id}}" style="margin-bottom:10px">

Javascript codes;

const cartButton = document.getElementsByClassName('add-to-card-button');

if (cartButton) {
    Array.from(cartButton).forEach(function(element) {
        element.addEventListener('click', addToCard);
    });
   }

function addToCard() {

    $.ajax({
        url: "/auth/check",
        context: document.body,
        success: function(status){
           if (status === "Auth")
           {
               addToCardForUsers();
           } else {
               addToCardForGuests()
           }
        }
    });

}

function addToCardForUsers() {

    $.ajax({
        type: 'POST',
        url: "/cart/add-product/"+ cartButton.dataset.id,
        context: document.body,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(){
                if(countProduct.text() == null) {
                    countProduct.text(1);
                } else {
                    countProducts =  Number(countProduct.text());
                    countProducts++;
                    countProduct.text(countProducts);
                }              
                Flash.success("Product succesfully added to your cart");
        }
    });
}

I want to get data attribute value of clicked button. I need to use it When I submit an ajax form. How can I get that ?

My button (There are as many buttons as the number of products)

<input value="Add To Cart" type="button" class="btn btn-success btn-sm btn-block add-to-card-button" data-id="{{$product->id}}" style="margin-bottom:10px">

Javascript codes;

const cartButton = document.getElementsByClassName('add-to-card-button');

if (cartButton) {
    Array.from(cartButton).forEach(function(element) {
        element.addEventListener('click', addToCard);
    });
   }

function addToCard() {

    $.ajax({
        url: "/auth/check",
        context: document.body,
        success: function(status){
           if (status === "Auth")
           {
               addToCardForUsers();
           } else {
               addToCardForGuests()
           }
        }
    });

}

function addToCardForUsers() {

    $.ajax({
        type: 'POST',
        url: "/cart/add-product/"+ cartButton.dataset.id,
        context: document.body,
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        },
        success: function(){
                if(countProduct.text() == null) {
                    countProduct.text(1);
                } else {
                    countProducts =  Number(countProduct.text());
                    countProducts++;
                    countProduct.text(countProducts);
                }              
                Flash.success("Product succesfully added to your cart");
        }
    });
}
Share Improve this question edited Jan 23, 2018 at 11:30 asked Jan 23, 2018 at 11:27 user9127206user9127206 2
  • Try, alert($(this).data('data-id')); – imanshu15 Commented Jan 23, 2018 at 11:31
  • gives undefined – user9127206 Commented Jan 23, 2018 at 11:32
Add a ment  | 

4 Answers 4

Reset to default 5

Change the way you bind your event listner to this,

$('.add-to-card-button').on('click', function () {
    addToCard();
    alert($(this).data('id'));
});

You should use:

function addToCard(e) {
    alert($(e.target).data('id'))
}

What you could do is grab the id in addToCart and pass that as a parameter to addToCardForUsers where you can use it in your endpoint string. And since you're using jQuery, perhaps use it to pick up the buttons and assign the function to them on the click event.

$('add-to-card-button').on('click', addToCart);

function addToCard() {
  const id = $(this).data('id');
  $.ajax({
    url: "/auth/check",
    context: document.body,
    success: function(status) {
      if (status === "Auth") {
        addToCardForUsers(id);
      } else {
        addToCardForGuests()
      }
    }
  });
}

function addToCardForUsers(id) {
  $.ajax({
    type: 'POST',
    url: "/cart/add-product/" + id,
    ...
  });
}
<input value="Add To Cart" type="button" class="btn btn-success btn-sm btn-block add-to-card-button" data-id="{{$product->id}}" style="margin-bottom:10px">

To get the data-id attribute value from above code on button click event:

$(this).data('id')

JSFiddler Demo: https://jsfiddle/682xdbkv/1/

发布评论

评论列表(0)

  1. 暂无评论