Dynamically Populating Select Menus Client-Side - Function
(Page 3 of 4 )
function fillItems( intStart ) {
var fTypes = document.form1.types
var fItems = document.form1.items
var a = atItems
var b, c, d, intItem, intType
Now that we've initialized all the variables, we do the all important 'intStart' check. This is in place for edit screens, where we already know the ID of the item. We can place in the body onload event, hand the ID as an argument to the function, and populate the field based on it. Here's the code.
if ( intStart > 0 ) {
for ( b = 0; b < a.length; b++ ) {
if ( a[b][1] == intStart ) {
intType = a[b][0];
}
}
for ( c = 0; c < fTypes.length; c++ ) {
if ( fTypes.options[ c ].value == intType ) {
fTypes.selectedIndex = c;
}
}
}
What I did here was go through the array, find that item, match it to the type, select the type, and set the 'intType'. The next piece will set an 'intType'; if not, 'intStart' is supplied. Just look to what the user has chosen in the 'types' select menu.
if ( intType == null ) {
intType = fTypes.options[ fTypes.selectedIndex ].value
}
Now the last piece. First, we empty what's currently in the 'items' menu, if anything exists. We iterate through the items array, find any items that match to 'intType', and throw them into the 'items' menu. As we go by each one, we check to see if its ID matches 'intStart'. If it does, it should therefore be selected, so we select it!
fItems.options.length = 0;
for ( d = 0; d < a.length; d++ ) {
if ( a[d][0] == intType ) {
fItems.options[ fItems.options.length ] = new Option( a[d][2], a[d][1] ); // no line-break here
}
if ( a[d][1] == intStart ) {
fItems.selectedIndex = fItems.options.length - 1;
}
}
}
</script>
So that's it. This is basically the most efficient way to accomplish the task. I've seen scripts where an extra function was created to handle the initial selecting of a pre-existing item ID for edit screens. But with this function, we are able to do it on the fly, in one function. Nifty ain't it?
Next: Conclusion >>
More JavaScript Articles
More By Justin Cook