Chandramohan
Chandramohan

Reputation: 46

How to get click event object data from dynamically created button using jQuery or JavaScript

I am collecting page button click events. Normally I am collecting the objects from statically created DOM elements. By using:

 $('input[type=button]').each(function () {
              $(this).bind('click', function () {
                  Console.log(this);
              });
          });

But when I add a new button dynamically like:

 vvar newBtn = document.createElement('input');
      newBtn.type = 'button';
      newBtn.setAttribute('id', 'JgenerateBtn');
      newBtn.setAttribute('value', 'JgenerateBtn');
      newBtn.onclick = function () { alert('javascript dynamically created button'); };
      var holderDiv = document.getElementById('holder');
      holderDiv.appendChild(newBtn);

after this code, New Button is created and event also triggering, but I'm not able to get the Event object by using, same above code.

 $('input[type=button]').each(function () {
          $(this).bind('click', function () {
              Console.log(this);
          });
      });

Please provide suggestion to get the dynamically created elements event object.

Upvotes: 1

Views: 5382

Answers (3)

palaѕн
palaѕн

Reputation: 73906

You should use the following:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#holder').on('click', ':button', function(event) {
    alert('testlink'); 
});

This will attach your event to any button within the #holder element, reducing the scope of having to check the whole document element tree and increasing efficiency.

More info here:-

Upvotes: 1

Gung Foo
Gung Foo

Reputation: 13558

The event object is handed to your click handler as the first argument.

$('input[type=button]').each(function () {
    $(this).bind('click', function (event) {
        Console.log(event);
    });
});

Upvotes: 0

nix
nix

Reputation: 3302

You may use on() for binding events on dynamically added elements. Like this:

$(document).on('click', 'input[type=button]', function(){
    console.log(this);
});

This is just for simple example, it is better to bind it on element closer to your button that is already on page when it first loads rather than on document.

Upvotes: 6

Related Questions