A More Complex Way of Building Replacement Combo Boxes
In part one we looked at an easy way to recreate the functionality of combo boxes, while also creating the ability to style them effectively across browsers. In this part, we're going to work on getting rid of the hard coding of option values in the event handlers for the options, and look at dealing with combo boxes that have more options. You'll need the source files from part one to build on, and your trusty text editor at your side.
A More Complex Way of Building Replacement Combo Boxes - Data Storage Format (Page 3 of 4 )
That was relatively easy to achieve, and while not a particularly beautiful solution, it does work and additional divs can be added as necessary. Doing this however results in more HTML code, which makes things harder to maintain and update. One way to cut down on the code necessary would be to keep the options in a separate file and have the script read the file and create the options on the fly. This way, we could easily add or remove options without modifying the script at all. Also, by making the different elements of the drop-down replacement modular, we can easily use the same options on more than one page. If you create a set of different source files, each with their own options in them, you have a library that you can use on any of your forms.
XML seems like the obvious choice of data storage formats, which is easy to code and easy to grab and play with using JavaScript. Create the following file in your text editor:
The DOCTYPE declares the elements we want to use and what is contained within them. It's very basic and very easy to maintain. You could come back to this in six months time, take one look and know exactly what's going on. Save it as options.xml.
Now we need to add some JavaScript to get and use the data we've just created. Back in the combo.js file, add the following function:
function getOptions() { if (window.ActiveXObject) { file = new ActiveXObject("Microsoft.XMLDOM"); file.async = false; file.load("options.xml); writeOptions(); } else { file = document.implementation.createDocument("","",null); file.load("options.xml"); file.onload = writeOptions; } }
The way that IE and FireFox open XML files is different, so the function that parses the options XML file needs to cater to both methods. A simple object-based detection determines whether ActiveX is available, and if so, proceeds to set the file variable to the Microsoft.XMLDOM object, load the xml file and call the next function. If ActiveX is not available, the script assumes FireFox and uses the .implementation method to create an instance of the XML file in the variable. Again, it calls the next function before ending.