Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - Dynamically Create Button and Attach Event Handler

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?

like image 462
senfo Avatar asked Jun 01 '11 17:06

senfo


People also ask

How do you add an event handler to a dynamic button?

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 .

How to dynamically add button in JavaScript?

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.

How can we call onclick function on dynamically created button in jQuery?

onclick = function () { alert("hi jaavscript"); };


2 Answers

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'); }); 
like image 139
Matt Ball Avatar answered Oct 06 '22 08:10

Matt Ball


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); }); 
like image 43
Schovi Avatar answered Oct 06 '22 06:10

Schovi