Using a For Loop to create drop-down list

Right. I’m trying to add <option> elements to a <select> list. It isn’t going too well! The option elements are years from 2004-2013. My code below successfully increments my year variable, but I’m obviously going awry with how I’m writing to the document. At the moment I get 10 separate select boxes instead of the single select list containing the 10 options for each year. If someone could point me in the right direction to resolve I’d be very grateful.

Code:


<body>
<script language="JavaScript">
<!-- start JS code hide

// loop to create the list


var year = 2003

for (var i=1; i <=10; i++)
{
	year++;
	document.write("<select name='years'>");
	document.write("<option>" + year + "</option>");

}


// end JS code hide -->
</script>
<form name="yearform">
</select>
</form>
</body>

The code inside the loop body gets executed each time the loop, loops.

Notice how a select menu has a single open and close <select> element, and in between those, are multiple <option> elements.

Since you want to create one menu, you dont want the <select> tags inside of the loop.

Thanks crmalibu. I literally just realised that once I loaded the page in FireBug (what a great little tool!)

Removing the <select> from the loop did indeed resolve.

var year = 2003
document.write(“<select name=‘years’>”);

for (var i=1; i <=10; i++)
{
year++;
document.write(“<option>” + year + “</option>”);

}

Thanks again for your help. :slight_smile: