I built a cascading dropdown in jquery, modified from a few examples. I added a feature to let the user "back up" and reselect an earlier dropdown. This reloads the next dropdown, and clears and disables the subsequent ones.
http://jsfiddle.net/goodeye/gA6GZ/
The problem is after the first time through, the select elements' change events are bound, so I think reloading new values is causing the later change events to fire.
I separated out the .change() bind, instead of chaining it. I previously had it chained before loading the select options. This helped the first time through, but not subsequent times.
For this problem, I'm specifically looking for a good approach to this sequence:
- avoid change()
- update the dropdowns
- set up change()
This question: Best way to remove an event handler in jQuery? has unbind() as the main answer, then a subsequent answer to use live(). The live() approach uses a class which is slightly confusing me, and didn't get as many votes.
To reproduce:
Select step 1, see step 2 fire.
Select step 2, see step 3 fire.
Select step 1 again, see step 2 fire.
then the trouble starts:
Select step 2, see step 3 fire twice.
Select step 3, see step 4 fire three times.
Select step 1 again, see step 2 fire twice.
etc.
It even gets worse; I'll see step 3 fire five times.
Some details:
In the real code, these load from a json ajax call. I removed that from the example, and added hard-coded options to simulate it, scoping this to just the event issue.
This starts out server-side, so the first dropdown is already "in" the html. The next three are loaded from (simulated) json calls.
These use classes for identification, because the real page has more than one set of these dropdowns. The code uses $(this) to be careful to work within the one set that was selected.
There is also a feature to 'auto select' if there's only one option, and move on to the next one. This code is in there, but the simulated examples all have more than one option, to avoid this issue for this question.
Thanks in advance for your ideas!