Dzhuneyt
Dzhuneyt

Reputation: 8701

jQuery On <select> Change Event Not Firing

I have the following in the header:

$('body').on('change', '#userFilter', function(){
   console.log('changed');
});

And this element is dynamically inserted on the page when a tab is clicked:

<select id="userFilter">
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

The problem is that when I change the dropdown nothing is shown in the console.

Upvotes: 16

Views: 24074

Answers (2)

Adil
Adil

Reputation: 148110

Wrap it in $(document).ready(function(){....}) so that the html control userFilter is added to DOM and available for javascript

$(document).ready(function() {
   $('body').on('change', '#userFilter', function(){
      console.log('changed');
   });
});

The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code, jQuery docs.

Upvotes: 21

Serj Sagan
Serj Sagan

Reputation: 30198

Although a bit unrelated to the OQ, if you got here because your select is not firing, make sure that at a previous time you didn't check the "Prevent this page from showing..." in the alert(). You'd need to close the tab and reopen that URL to get that to fire visibly again.

Upvotes: 1

Related Questions