Binding DropDownList With JQuery And XML.

Vishalneeraj-24503
Posted by Vishalneeraj-24503 under jQuery category on | Points: 40 | Views : 314
Add jQuery library reference in head section and place one dropdown on the page.
Add one list item with select as it's value.


<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem>Select</asp:ListItem>
</asp:DropDownList>

<asp:Label ID="Label1" runat="server" Text=""/>

Following is the Cities.xml file i'm using to bind dropdownlist using jquery.
<!--?xml version="1.0" encoding="utf-8" ?-->
<cities>
<city>
<name>Mumbai</name>
<id>1</id>
</city>
<city>
<name>Delhi</name>
<id>2</id>
</city>
<city>
<name>Banglore</name>
<id>3</id>
</city>
<city>
<name>Chennai</name>
<id>4</id>
</city>
</cities>

<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax(
{
type: "GET",
url: "Cities.xml",
dataType: "xml",
success: function(xml)
{
var dropDown = $('#<%=DropDownList1.ClientID %>');
$(xml).find('City').each(function()
{
var name = $(this).find('name').text();
var id = $(this).find('id').text();
dropDown.append($("<option></option>").val(id).html(name));
});
dropDown.children(":first").text("--Select--").attr("selected", true);
}
});
$('#<%=DropDownList1.ClientID %>').change(function()
{
var ddl = $('#<%=DropDownList1.ClientID %>');
var selectedText = $('#<%=DropDownList1.ClientID %> option:selected').text();
var selectedValue = $('#<%=DropDownList1.ClientID %>').val();
document.getElementById('Label1').innerHTML = "You selected " + selectedText + " With id " + selectedValue;
});
});
</script>

Comments or Responses

Login to post response