Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery On <select> Change Event Not Firing

Tags:

jquery

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.

like image 990
Dzhuneyt Avatar asked Aug 09 '12 14:08

Dzhuneyt


2 Answers

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.

like image 53
Adil Avatar answered Sep 21 '22 13:09

Adil


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.

like image 45
Serj Sagan Avatar answered Sep 22 '22 13:09

Serj Sagan