1

I’ve read many posts already on the $.each and newly added elements + event attachment. Many of the current Questions regarding this topic on StackOverflow don’t seem to work for me. $.on() is normally recommended since it allows us to append new elements and still maintain a single event listener + handler.

In my current code:

1.$(‘input[type="checkbox"]’).on(“change”, function(e){});

  1. //I do a logical if-statement, if(this.checked) else

  2. //With-in the if-statement I run $.each, however, once I have appended new element in this context a new li to the ul, it stops working.

Out of the curiosity has anyone encountered something like this before, and if YES, how have you folks solved this?

Some StackOverflow posts I have already seen:

jQuery $(element).each function doesn't work on newly added elements

jquery: dynamically appending li items to ul then adding click, but click runs through each li

Event binding on dynamically created elements?

Community
  • 1
  • 1
John Smith
  • 465
  • 4
  • 15
  • 38

1 Answers1

1

Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.

As you are creating elements.

You need to use Event Delegation. You have to use .on() using delegated-events approach.

General Syntax

$(document).on(event, selector, eventHandler);

Ideally you should replace document with closest static container.

Example

$(document).on('change', 'input[type="checkbox"]', function(){
  //Your code
});
Satpal
  • 132,252
  • 13
  • 159
  • 168