0

I am adding dynamical the below element to my table.

As you can see when you press the +-button you get a new button Add Product2 inserted below in the table.

Find below my minimum example:

$(".btn.btn-dark.btn-sm").on("click", this.clickDispatcherTable.bind(this))
$(".btn.btn-primary.btn-sm").on("click", this.ourClickDispatcher.bind(this));

function clickDispatcherTable(e) {
  let plusButton = $(e.target).closest(".btn.btn-dark.btn-sm")

  if (plusButton.hasClass("product2")) {
    let plusButtonParent = plusButton[0].parentElement.parentElement;
    plusButtonParent.insertAdjacentHTML('afterend', `
    <tr>
      <td></td>
      <td>
        <button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
                                            Add Product2
                                        </button>
      </td>
    </tr>
            `)
  }
}

function ourClickDispatcher(e) {
  console.log("event")
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table style="float: left;" class="table table-bordered">
  <tbody>
    <tr>
      <td>Product 2</td>
      <td>
        <button type="button" data-exists="product2" class="btn btn-primary btn-sm product2">
                                            Add Product2
                                        </button>
        <button type="button" class="btn btn-dark btn-sm product2">+</button>
      </td>
    </tr>
  </tbody>
</table>

When I press the button that is at the top I get the console output event. When I press the button - which got inserted by JQuery, the console.log event does not get fired.

Any suggestions why the event is not loaded properly?

Carol.Kar
  • 4,581
  • 36
  • 131
  • 264
  • Also: https://stackoverflow.com/questions/6658752/click-event-doesnt-work-on-dynamically-generated-elements/6658774#6658774 – Cᴏʀʏ Apr 18 '18 at 19:59
  • @Cᴏʀʏ Thx for your reply! Would you be so kind to give me a brief example for my case? Because I am using the "parent" element as selector as shown in the answers. I appreciate your reply! – Carol.Kar Apr 18 '18 at 20:04
  • 1
    A "parent" element in this case is a static element that exists when the page loads and doesn't change, not the button doing the adding. For example, your `` is a static parent. You could give that `
    ` an ID like "products-table" (`
    `), and then change your click-binding to: `$("#products-table").on("click", ".btn.btn-dark.btn-sm", this.clickDispatcherTable.bind(this));`
    – Cᴏʀʏ Apr 18 '18 at 20:54

0 Answers0