faqts : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

45 of 62 people (73%) answered Yes
Recently 6 of 10 people (60%) answered Yes

Entry

How can I dynamically create a SELECT list when the document loads?

Mar 3rd, 2000 18:58
Martin Honnen,


http://www.faqts.com/knowledge-base/view.phtml/aid/1181/fid/178/lang/en
shows how to dynamically add OPTIONs to a SELECT list or delete them 
once the document is completely loaded. Often however you want to 
dynamically build a select list but have the data around when the page 
loads. In this case it is much easier to simply document.write the 
OPTIONs (or maybe the complete SELECT tag) as that way you save 
yourself the trouble of needing to call history.go(0) for some versions 
of NN to get the display refreshed.
So here comes an example which builds some SELECT list dynamically when 
the page loads:

<HTML>
<HEAD>
<SCRIPT>
function writeOptions (n1, n2) {
  for (var i = n1; i <= n2; i++)
    document.write('<OPTION VALUE="' + i + '">' + i + '\n');
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="formName">
Day
<SELECT NAME="day">
<SCRIPT>
writeOptions(1, 31)
</SCRIPT>
</SELECT>
Month
<SELECT NAME="month">
<SCRIPT>
writeOptions(1, 12)
</SCRIPT>
</SELECT>
Year
<SELECT NAME="year">
<SCRIPT>
var now = new Date();
var year = now.getFullYear ? now.getFullYear() : now.getYear();
year = year < 1900 ? 1900 + year : year;
writeOptions(year, year + 20);
</SCRIPT>
</SELECT>
</FORM>
<SCRIPT>
var d = now.getDate();
document.formName.day.selectedIndex = d - 1;
var m = now.getMonth();
document.formName.month.selectedIndex = m;
document.formName.year.selectedIndex = 0;
</SCRIPT>
</BODY>
</HTML>