Facelift! Linked Select
The linked select (or chained drop-down if you prefer) is a simple solution to an old problem. If you build a site with it’s own database, and assuming there’s a big jumble of categories and sub-categories and sub-sub-categories etc., you may need javascript to associate values in 1 select element, with the values in another (based on some hierarchical structure). And when you do, there are a number of ways you can go about it.
One of the methods I used (last time I had this problem) was to create a hidden select and shuffle all the spare (child) options off to it when filtering according to the value of a parent select element. I wrote a Moo class for it too! Today we’re going to give it a facelift!
Before we can improve, we need to understand. So let’s look what this class does:
Old school
Firstly we create the ghost element and move all the child select’s options to it.
Then, in the filter method, we remove each option above the offset. The offset is the starting point from which our child’s options will be altered – this is so that we can have static options or even a placeholder option at the beginning of the child select’s options list. Then we filter through the options in the ghost select and move applicable options back to the child select based on the value of a particular attribute on the parent select.
If a ‘select’ value is passed then we attempt to select the option with that value.
Lastly, in the filter method, we enable/disable the child depending on whether there are options (after the offset) in the child select. That’s all there is to it – it’s a simple plugin after all. Now let’s see how we can improve it.
New school
Firstly, there are a number of ways we can simplify the options we give this class, while keeping the same flexibility:
The previous options were a little confusing; basically we need to be able to specify which attribute the parent options filter on, and which attributes on the child are filtered by. We’ve renamed ‘child’ to ‘selected’ for the sake of clarity.
Our new initialize method looks quite like the old, but we’re assuming less about the environment by including a ‘container’ option but defaulting to document.body. Because of our simpler options we can also get away with defining fewer variables, and still have readable code!
Our filter method also looks pretty much the same, but without the unnecessary variable declarations. We’re also erasing selected and disabled properties instead of setting them to blank. That’s it folks!
demo – old school – new school



![Always return [Explore #2] A photo on Flickr](http://farm5.static.flickr.com/4098/4881930066_b3d279bcf9_s.jpg)


