I would like to dynamically add a button control to a table using jQuery and attach a click event handler. I tried the following, without success:
$("#myButton").click(function () { var test = $('<button>Test</button>').click(function () { alert('hi'); }); $("#nodeAttributeHeader").attr('style', 'display: table-row;'); $("#addNodeTable tr:last").before('<tr><td>' + test.html() + '</td></tr>'); });
The above code successfully adds a new row, but it doesn't handle adding the button correctly. How would I accomplish this using jQuery?
To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click . We're saying that onclick of the button, the p tag with a class of moreInfo should display block .
In vanilla JavaScript, you can use the document. createElement() method to programmatically create an HTML button element and set its required attributes. Then to append the button to a container, you can use the Node. appendChild() method.
onclick = function () { alert("hi jaavscript"); };
Calling .html()
serializes the element to a string, so all event handlers and other associated data is lost. Here's how I'd do it:
$("#myButton").click(function () { var test = $('<button/>', { text: 'Test', click: function () { alert('hi'); } }); var parent = $('<tr><td></td></tr>').children().append(test).end(); $("#addNodeTable tr:last").before(parent); });
Or,
$("#myButton").click(function () { var test = $('<button/>', { text: 'Test', click: function () { alert('hi'); } }).wrap('<tr><td></td></tr>').closest('tr'); $("#addNodeTable tr:last").before(test); });
If you don't like passing a map of properties to $()
, you can instead use
$('<button/>') .text('Test') .click(function () { alert('hi'); }); // or $('<button>Test</button>').click(function () { alert('hi'); });
Quick fix. Create whole structure tr > td > button; then find button inside; attach event on it; end filtering of chain and at the and insert it into dom.
$("#myButton").click(function () { var test = $('<tr><td><button>Test</button></td></tr>').find('button').click(function () { alert('hi'); }).end(); $("#nodeAttributeHeader").attr('style', 'display: table-row;'); $("#addNodeTable tr:last").before(test); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With