Reputation: 1051
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.
Upvotes: 0
Views: 1583
Reputation: 104775
Event delegation my friend:
$("#friendsList").on("change", "#AllowedFriends", function () {
// do something
});
Upvotes: 1
Reputation: 16723
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
Upvotes: 1
Reputation: 5050
Since your created the element after, you need to use ON
$(document).on("change", "#AllowedFriends", function(){
// do something
});
Upvotes: 1