Ivan
Ivan

Reputation: 433

Click only one time on each dynamic generate element

I have dynamically generated button that comes from ajax call

html += '<button type="button" class="btn btn-primary buy-s-product" data-price="'+ json.result[key].price +'" data-productname="'+ json.result[key].product_name +'" data-productid="'+ json.result[key].product_id +'">Buy</button>';

Each product has its own details but button is same for all of them. how can I make such that once the button is clicked for the current product, it will execute only one time and no more for current product?

this is what I have attempted:

$(document).on('click', '.buy-s-product', function(){

var product_id = $(this).data('productid');
var product_name = $(this).data('productname');
var price = $(this).data('price');

$('#input-order').trigger('change');

});

Upvotes: 0

Views: 49

Answers (1)

antonku
antonku

Reputation: 7675

You can add a class to the button when it's clicked and adjust the selector to exclude elements with this class:

$(document).on('click', '.buy-s-product:not(".clicked")', function(){

  console.log('clicked');
  
  var product_id = $(this).data('productid');
  var product_name = $(this).data('productname');
  var price = $(this).data('price');

  $('#input-order').trigger('change');
  $(this).addClass('clicked');
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="buy-s-product">TEST</button>

Upvotes: 1

Related Questions