Saturday, May 24, 2008

How do i load select object with javascript

To load a select object with javascript we will write two simple functions called
doLoad,loadSelect passing in the select object reference and the data to be loaded
Here we assume the data is comming from an XML file from the server. let's first take
a look at the XML file before we go ahead to write the function
data.xml

<?xml version='1.0' encoding='utf-8'?>
<States>
<state stateName='Anambra' stateCode='100'/>
<state stateName='Adamawa' stateCode='101'/>
<state stateName='Bauchi' stateCode='102'/>
<state stateName='Edo' stateCode='103'/>
.
.
.
</States>

if we wanted to load this data in to a select object we first define our doLoad function

function doLoad(xmlDoc)
{

/**Here we pick up the select object we want
* to load based on the id we assigned to it
*/
var selObject=document.getElementById('SelectId');
if(!selObject)
{return;}
/**
* Next we get the state element of the XML file
* This will make docRoot an array of object we could
*loop through
*/
var docElem=xmlDoc.getElementsByTagName('state');

/**
* We call the loadSelect function to do the actual work
* Passing it the selectObject and the docElem
*/

loadSelect(selObject,docElem);
return;
}

And that ends the doLoad function, next we look at the loadSelect function


function loadSelect(targetObj,data)
{
if(!targetObj || !data)
{return;}

for(var k=0;k<data.length;k++)
{
var options=data[k];
var option=document.createElement('option');
option.value=options.getAttribute('stateCode');
option.appendChild(document.createTextNode(options.getAttribute('stateName')));
targetObj.appendChild(option);
option=null;
options=null;

}
return;
}

And that does the loading of the XML data into the select object
Note that the structure of the XMl data matters a lot when it comes to loading
the Select Object because Javascript has a number of ways of dealing with
XMl data with its DOM capability, i have used the most basic way of dealing
with XML using javascript DOM

No comments: