0

I have made a button like this in my main.js file :

del_btn = document.createElement("button");
del_btn.className = "btn btn-light btn-sm ";
del_btn.type = "button";
del_btn.id = "delete_btn";
del_btn.innerHTML = 'X';

and put this in a <tr> which is in my index.html page. I wanted to make this alert something when the button gets clicked on. So I wrote a code that looks like this in my main.js file as well.

$("#delete_btn").click(function() {
    alert("delete button clicked!!");
});

But nothing happens when I click on the button which id is 'button'. I have no idea why this doesn't work. Does anyone know why this is not working? Any advice would be appreciated!!!

Andreas
  • 21,535
  • 7
  • 47
  • 56
  • Possible duplicate of [In jQuery, how to attach events to dynamic html elements?](https://stackoverflow.com/questions/1359018/in-jquery-how-to-attach-events-to-dynamic-html-elements) – Mohammad Dec 08 '18 at 09:10
  • 2
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Andreas Dec 08 '18 at 09:11
  • `$("tr").on('click', '#delete_btn', function() { alert("delete button clicked!!"); });` Use like this, this would work, Using duplicate id is not a good practice – Akhil Aravind Dec 08 '18 at 09:13

2 Answers2

0

as per latest jquery try below

$(document).on('click', "#delete_btn", function() {
    alert("delete button clicked!!");
});
AG_
  • 2,589
  • 3
  • 20
  • 32
0

I am assuming that you are appending the delete_btn to document at right place like,

appendTo = document.getElementById("idToWhomeYouAppend")
appendTo.append(del_btn)

As you are creating del_btn button using plan js, attach the onclick in same way. e.g.

del_btn.onclick = function() {
    alert("delete button clicked!!");
};

So no need to register onclick using jquery but if you want to use jquery make sure jquery based code gets executed after del_button is getting appended in the dom.

Mukund
  • 393
  • 2
  • 7