0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
abalter
  • 9,663
  • 17
  • 90
  • 145

1 Answers1

2

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.

Siada
  • 103
  • 1
  • 9
  • Hmmm. That didn't work. http://plnkr.co/edit/Dxem7VkfbDD2bzVGOoEt. I was able to find a workaround that I added as an edit to my post. – abalter May 26 '15 at 00:38
  • It didn't work because you wrapped your existing event in the event I provided instead of replacing it! If you have a look here http://plnkr.co/edit/MGro463L3muU1pVyf9D7?p=preview you'll see what I mean. – Siada May 26 '15 at 07:36
  • Aha, I see. Thanks. I see the problem now. It's all because Plunker won't let me load the javascript at the bottom of the index page (as I do in the "real" version). – abalter May 26 '15 at 18:51