0

I have a Layout page called Layout.cshtml On that page I have a div whose ID is friendsList

I have a View called Users.cshtml On that page I have a select tag whose ID is AllowedFriends and its value comes from the database

Now, I need to add that AllowedFriends to friendsList, so I write the JQuery as below

$("#friendsList").append($("#AllowedFriends"));

Upto here it is fine.

Now I want to show an alert or do something when user changes the selection on AllowedFriends.

So I write the JQuery as below :

$("#AllowedFriends").change(function () {
 // do something
});

But this does not work. I have tried to debug it. I used break point but this event never executes.

Khushi
  • 1,031
  • 4
  • 24
  • 48

3 Answers3

1

Since your created the element after, you need to use ON

$(document).on("change", "#AllowedFriends", function(){
 // do something
});
Fabien TheSolution
  • 5,055
  • 1
  • 18
  • 30
1

You need to ensure that your event handler is bound to the element even if it doesn't exist in the DOM yet when the handler is declared. This is best achieved by working off the document object as we are assured it will always exist at the time of the event handler declaration:

 $(document).on("change", "#AllowedFriends", function(){
     //Glorious code!
  });

This is event delegation, and in simple terms it means that elements higher up the DOM tree listen for events that bubble up from its descendents (in this case, document is listening to the change event on its descendent element with the ID of #AllowedFriends

Mister Epic
  • 16,295
  • 13
  • 76
  • 147
1

Event delegation my friend:

$("#friendsList").on("change", "#AllowedFriends", function () {
    // do something
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157