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:
<?xml version "1.o" encoding="ISO-8859-1" standalone="yes"?>
<!DOCTYPE options [
<!ELEMENT options (option+)>
<!ELEMENT option (#PCDATA)>
]>
<options>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
<option>Option 7</option>
<option>Option 8</option>
<option>Option 9</option>
<option>Option 10</option>
</options>
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.
Next: Extracting the Data >>
More Style Sheets Articles
More By Dan Wellman