Khushi
Khushi

Reputation: 1051

Do something when user changes the selection on select-option using JQuery

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

Answers (3)

tymeJV
tymeJV

Reputation: 104775

Event delegation my friend:

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

Upvotes: 1

Mister Epic
Mister Epic

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

Fabien TheSolution
Fabien TheSolution

Reputation: 5050

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

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

Upvotes: 1

Related Questions