Lets say you have 10 selects.
Code:
function attachBehaviors() {
// Attach event handler to your select objects
for (i=1 ; i<11 ; i++){
var s = document.getElementById("select"+i);
if( s ) {
s.onchange = function(){selectCallback(s);};
}
}
}
But what you REALLY want is this:
Instead of IDing it select2, make the id id=select_sloganS
select3 is select_titleS
Now, we make an array of our selects - put this aomewhere up top.
Code:
selectIDs=['companyName','sloganS','titleS'];
This will create an array with 3 things in it. The nice thing here, is you just add a new element to the array, make sure you create the html and the following code will automatically create it.
Note: arrays start with zero, not 1
The numeric reference is called an 'index'
eg: selectIDs[2] will contain the string 'titleS'
Code:
function attachBehaviors() {
// Attach event handler to your select objects
for (i=0 ; i<selectIDs.length ; i++){
var s = document.getElementById("select_"+selectIDs[i]);
if( s ) {
s.onchange = function(){selectCallback(s,selectIDs[i]);};
}
}
}
Note that selectIDs[i] will loop and contain each value each time through. It adds select_ to the name to reference the select, and we pass it to the selectCallback() function, which then gets rewritten like so:
Code:
function selectCallback(s,changevar)
{
// This function gets called when selection changes
if( s.selectedIndex == -1 ) return;
var v = s.options[s.selectedIndex].value;
var theobjtoChange=document.getElementById(changevar);
switch(v) {
case '443':
// Change Company Name Font
theobjtoChange.style.fontFamily='Arial';
break;
case '444':
theobjtoChange.style.fontFamily='verdana';
break;
default:
// Do nothing for other selections
break;
}
}
Lets take it one step further
Make 1 special 'lookup' array
Code:
fontData=[];
fontData[443]='Arial';
fontData[444]='verdana';
... etc ...
And our code becomes simpler AND permanent.
Code:
function selectCallback(s,changevar)
{
// This function gets called when selection changes
if( s.selectedIndex == -1 ) return;
var v = s.options[s.selectedIndex].value;
var theobjtoChange=document.getElementById(changevar);
theobjtoChange.style.fontFamily=fontData[v];
}
Any lights coming on?
Mastering Javascript Arrays