The JavaScript Diaries: Part 12 - Multiple Array Types | 3
[previous]
The JavaScript Diaries: Part 12 - Multiple Array Types
Associative Arrays
Another type of array is called an associative array. With this type of array, you can call the element with a string instead of a number. It's easier to use but not useful in a loop because there are no numbers. This type of array can be used for many different things. Let's create one and see what we can do with it.
var musicType = new Array(); musicType["blues"] = "The Thrill is Gone"; musicType["rock"] = "Proud Mary"; musicType["gospel"] = "Amazing Grace"; musicType["country"] = "Your Cheatin' Heart"; var selectType=prompt("What type of music do you like", "") if ((selectType=="blues") || (selectType=="rock") || (selectType=="gospel") || (selectType=="country")) alert("I think '" + musicType[selectType] + "' is a good song") else alert("Well, that's nice music too.")
|
Another technique would be to use it in a drop down list. In an external file (or the head section) place the following code:
var offInfo = new Array(); offInfo["president"] = "Michael Smith: 555-1212"; offInfo["vpresident"] = "Sherry Gables: 555-4578"; offInfo["treasurer"] = "Nick Adams: 555-1916"; offInfo["secretary"] = "Leslie Jones: 555-8745"; function displayOff(offInfo,entry) { var nameTele=offInfo[entry]; document.musicForm.nameTeleBox.value=nameTele; }
In the body section:
<form name="musicForm"> <strong>Select Officer:</strong> <select onChange = "displayOff(offInfo,this.options[selectedIndex].value);"> <option value=""> <option value="president">President <option value="vpresident">Vice President <option value="treasurer">Treasurer <option value="secretary">Secretary </select> <p> <strong>Name/Telephone:</strong> <input class="box" type="text" name="nameTeleBox" value="" readonly size="35"> </form>
This one displays a drop down selection box. From that box, a corporate officer can be selected. The officer's name and telephone number will appear below. It should look like this:
You could use CSS to remove the border from the second box to streamline the appearance for your layouts.
Conclusion
In our next installment we wrap up our study of arrays by looking at the different properties and methods associated with them and how to go about manipulating data within them.
Continue on to "The JavaScript Diaries: Part 13"
[previous]
Created: January 20, 2006
URL: