Search code examples
jqueryonchangejquery-eventsplunker

JQuery on("change"...) method not working in Plunker


I created this Plunk to demonstrate and discuss a shopping cart I'm developing that is in action here (while it lasts).

In the "real" one, selecting a species fills the Variety drop-down. However, it's not working in the Plunk.

In fact, $('#species-select').on('change', ... is never firing.

Must be some peculiarity of how Plunks work. Any suggestions/workarounds?

Edit Just to add something -- in the "real" version, I load the javascript at the bottom of the page. Plunker doesn't like that. I was able create a workaround by adding to the header:

<script type='text/javascript'>
  $(document).ready(function(){
      $('#species-select').on('change', function() {
      var variety_key = $('#species-select').val();
      console.log( "species changed to " + variety_key);
      alert( "species changed to " + variety_key);
      $('#variety-select').empty();
      fillVarietiesList(variety_key);
    });
  });
</script>

http://plnkr.co/edit/91FYs44DuLkS19YPLzd6?p=info

Further Update That still didn't quite work because I couldn't add items to the shopping cart. I found this did the trick:

<script type='text/javascript'>
  $(document).ready(function(){
      $.getScript('products.js');
      $.getScript('fill_selects.js');
      $.getScript('shopping_cart.js');
      $('#species-select').on('change', function() {
      var variety_key = $('#species-select').val();
      console.log( "species changed to " + variety_key);
      alert( "species changed to " + variety_key);
      $('#variety-select').empty();
      fillVarietiesList(variety_key);
    });
  });
</script>

http://plnkr.co/edit/91FYs44DuLkS19YPLzd6?p=preview


Solution

  • It's because as the jQuery runs it's hooking events onto dom elements that don't exist, so it has nothing to attach to. This can be fixed by switching your hook to an 'on' event:

    $(document).on('change','#species-select', function...
    

    I hope this makes sense.