Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

STORING COMBO BOX 'OPTIONS AND THEIR VALUES' IN AN EXTERNAL .JS FILE.

Status
Not open for further replies.

seba070707

Programmer
Joined
Aug 6, 2001
Messages
13
Location
AR
Hello!! I am Seba from Argentina.

I am building a big web site, that's why I posted a lot of questions and I'll post more!
My question now is: CAN I STORE COMBO BOX OPTIONS (AND THEIR VALUES) IN AN EXTERNAL .JS FILE????

In my site, a lot of pages will have the same combo box with the same options and values and I think that it would be better if I store all the combo information in ONE JS file. Because it will be easier to UPDATE in the future.

If it is possible, please tell me how to call the options and values that are stored in the JS file and 'carry' them to the HTML page. Please, make a small example if possible.

THANKS!!!!!!!
 
This is a good idea - but really the server could do all of this so much easier for you - of course you may not have that facility available.

The way I have done it in the past is to use arrays because they are ideal for looping into a select box. Make a multidimensional so you have the value and text right there:

...
var data = new Array();
data[0] = new Array("text","value");
...


Then when putting these in your SELECT you can make up the options from one array.

// This would be stored externally.
var data = new Array();
data[0] = new Array("dog","brown");
data[1] = new Array("cat","black");
data[2] = new Array("bird","yellow")

function insertItems(selectBox){
// reset the select box to have the number of options in the array
selectBox.options.length = data.length;
var options = selectBox.options;
// Loop thru data inserting the information into value and text.
for(var j=0;j<options.length;j++){
options[j].text = data[j][0];
options[j].value = data[j][1];
}
}


So how do you access the data? Well it is read from the js file like any other JavaScript - so the arrays are just variables, just like if you had written them in. Just make sure you don't have variables with the same name on the page, and make sure you read the js file before using any of the contents - just plonk it at the top of the page so it is read first.



There are many ways to create SELECT boxes dynamically - by creating new elements - but sometimes that is tedious - however have a look here:


;-)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top