1

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, plus bind is deprecated AFAIK.
Why its not dynamically created elements objects is not logged in my code..can u explain difference between this?
@chandramohan Because events can only be bound to an element that are existing on page when it loads, so dynamically added elements are not selected on your code. Read Direct and Delegated events on the on() link above to better understand.
No prob. Hope you get something from my poor explanation. :)
Very nice! Worked for me
1

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:-

Comments

0

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);
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.