Monday, July 14, 2008

Dynamically generate select options in xhtml

This example shows how to generate options for select tag in HTML or XHTML.

<?xml version="1.0" ?>
<html xmlns=""
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript">
var xhtmlNS = "";
function generateOptions( ){
//Get the select via DOM
 var vSelect1 = document.getElementById("Select1");

 var i;
 for( i = 0 ; i < 10; i ++ ){
  //Created the option element 
  var vOption = document.createElementNS(xhtmlNS, "option");
  //Set the value
  vOption.setAttributeNS( null, "value", "value" + i );
  //Create the textnode for the option
  var vText = document.createTextNode( "text"+ i );
  //Append the textnode to the option element
  vOption.appendChild( vText );
  //Append the option element to the select element
  vSelect1.appendChild( vOption );
<body onload="generateOptions()">
<form id="selectForm">
<select id="Select1"></select>


Post a Comment

<< Home