Page

DropDown List With JQuery and XML

<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>Surat</name>
    <id>3</id>
  </city>
  <city>
    <name>Bareilly</name>
    <id>4</id>
  </city>

</cities>


//Add this script in head section of page.


<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>

No comments:

Post a Comment