Wednesday, April 15, 2009

Fill DropDownlist with javascript and xmlHttp.

Fill DropDownlist/Combobox/Select with javascript and xmlHttp and JQuery.

Reading XML files with JQuery is very easy nowadays. we can use ajax(JQuery) to get Xml file asynchonously on client machine. then We can fill options with nodes in xml file. Suppose we have select/option on my html page.

<select id="drpStudents">
</select>


We have xml file of students which required to fill in select/option list.

<?xml version="1.0" encoding="utf-8" ?>
<students>
<student id="1">
<name>
<lname>
dhameliya
</lname>
<fname>
haresh
</fname>
</name>
</student>
<student id="2">
<name>
<lname>
Patel
</lname>
<fname>
Naresh
</fname>
</name>
</student>
</students>


and we want to fill select/option with JQuery. here is the function to fill dropdown with javascript and xmlHttp using JQuery this.You have to include referance of JQuery on your page to accomplish this task..

JQuery can be downloaded from http://docs.jquery.com/Downloading_jQuery

function FillDropdownList(XmlPath)
{
$(document).ready(function()
{
$.ajax({
type: "GET",
url: XmlPath,
dataType: "xml",
success: FillData
});
});
function FillData(xml)
{
//Search every Student and Extract Name to fillup dropdownlist.
$(xml).find("student").each(function()
{
var drpStudents=document.getElementById("drpStudents");
drpStudents.options[drpStudents.options.length]=new Option($(this).find("fname").text(),$(this).attr("id"));
});
}
}


this function Get path of xml file as input parameter..thats done.

thanks..
happy programming..