0

I have this html product code:

<div id="new-product-content">
   <div class="col-md-3 col-sm-6 col-xs-12">

    // here code product

     <div class="delete-product"> 
       <a>Detele</a>
     </div>

  </div>
</div>

<div id="products-div">

JQuery Code:

  $(document).ready(function() {
    var i = 0;    
  $('.add-new-product').on('click', function() {

    // here just clone the product when chick on (.add-new-product) button
    // every thing is fine with clone 

    var $clone = $('#new-product-content > div').clone();
    $clone.appendTo('#products-div');

      i++;  
      // here I try to put id in each product
      $('#new-product-content > div').attr('id', 'row'+ i);

      // here to put id in 
      $('.delete-product > a').attr('id',i);

    });

  });  

Here in jQuery code I clone the product in many times, then put the id for each product, and put the same id for delete button that he can delete it if he wish.

So what I need to delete product after he add it ?

1 Answers1

0

You don't need any ID if you use a class like .product to define a product.
Than use jQuery's .on() method with dynamic event delegation to remove the element by going from the clicked Event.target to the .product by using .closest() :

jQuery($ => { // DOM ready and $ alias in scope

  let i = 0;

  const template_product = (html="") => `<div class="product col-md-3 col-sm-6 col-xs-12">
    <div>${html}</div>
    <button type="button" class="delete-product">Delete</button>
  </div>`;

  const addProduct = () => $('#products').append(template_product(`Product: ${++i}`)); 
  const deleteProduct = (ev) => $(ev.target).closest('.product').remove();


  $('.add-product').on('click', addProduct);
  $('#products').on('click', '.delete-product', deleteProduct);

});
<button type="button" class="add-product">ADD PRODUCT</button>
<div id="products"></div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

Without event delegation:

another way I use often is to declare that "Delete" button action upfront:

jQuery($ => { // DOM ready and $ alias in scope

  const newProduct = (html='') => $('<div/>', {
    class: 'product col-md-3 col-sm-6 col-xs-12',
    html: `<div>${html}</div>`,
    appendTo: '#products',
    append: $('<button/>', {
      class: 'delete-product',
      type: 'button',
      text: 'Delete',
      click() {
        $(this).closest('.product').remove();
      }
    })
  });


  let i = 0;
  $('.add-product').on('click', () => newProduct(`Product: ${++i}`));

});
<button type="button" class="add-product">ADD PRODUCT</button>
<div id="products"></div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

even if it respects the principles of templating and encapsulated component - the above might look a bit complicated to a fresh developer.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313