Ammar Iqbal
asked on
Populating dropdown lists using jquery
I Have one drop down list containing the elements {A,B,C,D,E,F}
I want to populate the other drop down list on the basis of slection of index in the first drop down list.
The problem is that if I need to do this in the Selected index change event ofthe first drop down list. I need to make auto postback is equal to true.
Which I do not want to do it.
I want to have this functionality to be  implemented  using jquery.(that is on the client side)
I want to populate the other drop down list on the basis of slection of index in the first drop down list.
The problem is that if I need to do this in the Selected index change event ofthe first drop down list. I need to make auto postback is equal to true.
Which I do not want to do it.
I want to have this functionality to be  implemented  using jquery.(that is on the client side)
ASKER
I need to get ddl list data from the database, and populate 2 with respect to the index change in ddl 1
To do that using jquery, you need to build a web service that can return this data in some structured format to your page.
There are a couple ways to do this. Â Unless you are talking about a giagantic range of choices, I suggest you pull down the entire choice/subchoice all at one, then use the logic in the example above.
So, instead of the first line defining DDdata in my above example, you will have a $.get() statement requesting the structure.
Then, you need a webservice (.asmx or .ashx) to create the value/pair list and send it back to the jquery so you can make a client-side variable holding all the values.
Something like the code sample below.
From their, provided you passed JSON to the .getJSON() method, the rest of the code in my sample above will work just fine.
There are a couple ways to do this. Â Unless you are talking about a giagantic range of choices, I suggest you pull down the entire choice/subchoice all at one, then use the logic in the example above.
So, instead of the first line defining DDdata in my above example, you will have a $.get() statement requesting the structure.
Then, you need a webservice (.asmx or .ashx) to create the value/pair list and send it back to the jquery so you can make a client-side variable holding all the values.
Something like the code sample below.
From their, provided you passed JSON to the .getJSON() method, the rest of the code in my sample above will work just fine.
var DDdata = []
$.getJSON("MyJSONService.ashx", function(data,textStatus){
if(textStatus === "success" ) {
DDData = data;
}
})
ASKER
my drop down lists are template fields in the DetailsView control. At which place , do i need to implment this client side functionality. I meanin the selected index event handler in code behind or some where else?
Well, it just got complicated :)
I'm going to need to see your DetailsView template code.
I'm going to need to see your DetailsView template code.
ASKER
Here is it..
I need to populate drop down list  in the header text "Sensor Name" with respect to the already db populated  ddl in the Header text "Sensor Type".
I want to do it using jquery c, because to do that on the server side , i need to make Auto Post back =true in the selected index cahnged event handler of ddl1. which i do not want to do it.
I need to populate drop down list  in the header text "Sensor Name" with respect to the already db populated  ddl in the Header text "Sensor Type".
I want to do it using jquery c, because to do that on the server side , i need to make Auto Post back =true in the selected index cahnged event handler of ddl1. which i do not want to do it.
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False" DataMember="Event" CellSpacing="0"
CellPadding="0" CssClass="normal" GridLines="None" >
<AlternatingRowStyle CssClass="odd" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<HeaderTemplate> Log Settings</HeaderTemplate>
<Fields>
<asp:TemplateField HeaderText="" SortExpression="id">
<InsertItemTemplate>
<asp:HiddenField ID="i_id" runat="server" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Event Type" SortExpression="type">
<ItemTemplate>
<asp:Label ID="ro_type" runat="server"></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="i_type" runat="server" DataMember="EventType" DataTextField="name" DataValueField="id" AppendDataBoundItems="true" Width="160">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Log Date" SortExpression="datetime">
<ItemTemplate>
<asp:Label ID="ro_datetime" runat="server" Text='<%# Bind("datetime")%>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:HiddenField ID="i_datetime" runat="server" />
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Event Date" SortExpression="eventtime">
<ItemTemplate>
<asp:Label ID="ro_eventtime" runat="server" Text='<%# Bind("eventtime")%>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="i_eventtime" runat="server" Text='<%# Bind("eventtime") %>' ></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Subject" SortExpression="subject">
<ItemTemplate>
<asp:Label ID="ro_subject" runat="server" Text='<%# Bind("subject")%>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="i_subject" runat="server" Text='<%# Bind("subject")%>' ></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Message" SortExpression="description">
<ItemTemplate>
<asp:TextBox ID="ro_description" runat="server" ReadOnly="true" Text='<%# Bind("description")%>'></asp:TextBox>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="i_description" runat="server" Text='<%# Bind("description")%>' TextMode="MultiLine" Width="150" Height="70px"></asp:TextBox>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sensor Type" SortExpression="i_instrumenttype">
<ItemTemplate>
<asp:Label ID="ro_instrumentype" runat="server"></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="i_instrumenttype" runat="server" DataMember="InstrumentType" DataTextField="name" DataValueField="id" AppendDataBoundItems="true" Width="160" >
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Sensor Name" SortExpression="instrument">
<ItemTemplate>
<asp:Label ID="ro_instrument" runat="server"></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="i_instrument" runat="server" DataMember="Instrument" DataTextField="name" DataValueField="id" AppendDataBoundItems="true" Width="160">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Severity" SortExpression="severity">
<ItemTemplate>
<asp:Label ID="ro_severity" runat="server"></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="i_severity" runat="server" DataMember="Severity" DataTextField="name" DataValueField="id" AppendDataBoundItems="true" Width="160">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Reported By" SortExpression="userid">
<ItemTemplate>
<asp:Label ID="ro_userid" runat="server" ></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:DropDownList ID="i_userid" runat="server" DataMember="aspnet_Users" DataTextField="UserName" DataValueField="UserId" AppendDataBoundItems="true" Width="160">
<asp:ListItem Text="" Value=""></asp:ListItem>
</asp:DropDownList>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Position" SortExpression="position">
<ItemTemplate>
<asp:Label ID="ro_position" runat="server" Text='<%# Bind("position")%>'></asp:Label>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="i_position" runat="server" Width="100"></asp:TextBox>
<asp:LinkButton ID="i_changePos" runat="server" CausesValidation="false" CssClass="button" OnClick="i_bthChangePos_Click">
<span class="ui-icon ui-icon-arrowreturnthick-1-e"></span>Change</asp:LinkButton>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField HeaderText="Image" SortExpression="image">
<ItemTemplate>
<asp:Image ID="ro_image" runat="server" ></asp:Image>
</ItemTemplate>
<InsertItemTemplate>
<asp:TextBox ID="i_image" runat="server" Width="100"></asp:TextBox>
<asp:LinkButton ID="i_changeImg" runat="server" CausesValidation="false" CssClass="button" OnClick="i_bthChangeImg_Click">
<span class="ui-icon ui-icon-arrowreturnthick-1-e"></span>Change</asp:LinkButton>
</InsertItemTemplate>
</asp:TemplateField>
<asp:TemplateField ShowHeader="false">
<ItemTemplate>
<asp:LinkButton ID="ro_new" runat="server" CausesValidation="False"
CommandName="New" CssClass="button" Visible="<%# IsAdmin %>">
<span class="ui-icon ui-icon-plus"></span>New
</asp:LinkButton>
<asp:LinkButton ID="ro_edit" runat="server" CausesValidation="False"
CommandName="Edit" CssClass="button" Visible="false">
<span class="ui-icon ui-icon-pencil"></span>Edit
</asp:LinkButton>
<asp:LinkButton ID="ro_delete" runat="server" CausesValidation="False"
CommandName="Delete" CssClass="button" Visible="false">
<span class="ui-icon ui-icon-trash"></span>Delete
</asp:LinkButton>
</ItemTemplate>
<EditItemTemplate>
<asp:LinkButton ID="e_update" runat="server" CausesValidation="False"
CommandName="Update" CssClass="button" Visible="false">
<span class="ui-icon ui-icon-check"></span>Update
</asp:LinkButton>
<asp:LinkButton ID="e_cancel" runat="server" CausesValidation="False"
CommandName="Cancel" CssClass="button" Visible="false">
<span class="ui-icon ui-icon-arrowreturnthick-1-w"></span>Cancel
</asp:LinkButton>
</EditItemTemplate>
<InsertItemTemplate>
<asp:LinkButton ID="i_insert" runat="server" CausesValidation="False"
CommandName="Insert" CssClass="button" Visible="<%# IsAdmin %>">
<span class="ui-icon ui-icon-check"></span>Save
</asp:LinkButton>
<asp:LinkButton ID="i_cancel" runat="server" CausesValidation="False"
CommandName="Cancel" CssClass="button" Visible="<%# IsAdmin %>">
<span class="ui-icon ui-icon-arrowreturnthick-1-w"></span>Cancel
</asp:LinkButton>
</InsertItemTemplate>
</asp:TemplateField>
</Fields>
</asp:DetailsView>
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
yes  iam getting an alert message , when i select some value from ddl1.  how to link this with the values in ddl2
SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
ASKER
yes you are right, the value in the scond srop down is changing ,but is not binding allthe respective values corrsponding tothe selected index of ddl1
Outstanding.  Now we're cooking with fire  :)
Have you ever created a Web Service (.asmx ) or Generic Handler ( .ashx) file? Â Your answer to this question will help me help you in the next step.
Have you ever created a Web Service (.asmx ) or Generic Handler ( .ashx) file? Â Your answer to this question will help me help you in the next step.
ASKER
no. I haven't created them before..
Ah, ok. Â Well, we need to do that first then. Â You will need to add a new file to your project. Â Let's go with the Web Service approach.
Here is a very nice tutorial. Â What you will end up doing is creating the web service that will send back a string of results that match the sub-choices of the selected index.
Before you can do that, you need to get familiar with web services.
http://www.codeproject.com/KB/webservices/myservice.aspx
Here is a very nice tutorial. Â What you will end up doing is creating the web service that will send back a string of results that match the sub-choices of the selected index.
Before you can do that, you need to get familiar with web services.
http://www.codeproject.com/KB/webservices/myservice.aspx
ASKER
ok i am doing it..but  isn't it goingto be a very long and complicated solution for populating a ddl on client sdie... I mean what is the main advantage of using a web service approach in solving this  problem
You stated you didn't want a post back. Â But you need to get the data from somewhere right? Â You *could* send all the possible sub menu choices when the page first loads or put them in an xml page and load them when the page loads and then get them when a choice is made from the first Drop Down. Â But I thought you wanted the solution to be more dynamic than this.
The PostBack that .net does is very similar to what we are working toward with one MAJOR exception. Â We are going to be using the ajax method built in to jquery that does not need to maintain ViewState. Â So, rather than passing the entire page back to the server, getting our new results, then passing the entire page back - we're just going to politely ask for a little packet of data be delivered by this Web Service. Â We will then take that little packet and change the values of the second drop down. Â What's beautiful about this approach is that it is technology-agnostic. Â That is, your drop down scenario here could be executed exactly the same in a plain-old HTML page.
I have to agree with you that when first working with web services it seems like a lot of work - but you have to trust me. Â It is THE most efficient way of handling dynamic data calls without .net postbacks.
The PostBack that .net does is very similar to what we are working toward with one MAJOR exception. Â We are going to be using the ajax method built in to jquery that does not need to maintain ViewState. Â So, rather than passing the entire page back to the server, getting our new results, then passing the entire page back - we're just going to politely ask for a little packet of data be delivered by this Web Service. Â We will then take that little packet and change the values of the second drop down. Â What's beautiful about this approach is that it is technology-agnostic. Â That is, your drop down scenario here could be executed exactly the same in a plain-old HTML page.
I have to agree with you that when first working with web services it seems like a lot of work - but you have to trust me. Â It is THE most efficient way of handling dynamic data calls without .net postbacks.
ASKER
The main point is that I need to do via client side scripting. I am working on this web service stuff, and looking forward to  follow your solution
Right. Â But client-side scripting needs the data. Â That's where the service comes in.
ASKER
and the data is coming from the Database table (Instrument) in the drop down list "i_instrument"
Um. Â Wait. Â What? Â Can you show me the rendered HTML and the data you are talking about?
ASKER
Take a look at the Sensro name (ddl2) and Sensor type(ddl1) in the details view control  control which i sent to  you
DataMember of yje Sensor name is "Instrument "which is a db table, and data member of sensor  type  is "InstrumentType"  which is  also a table.
For ddl1 i have populated it from instrument type , and for every selected  value of  instriument type in ddl1 , I need to populate the ddl2, the corressponding valuesfrom instrument,
but the point ihat i need to do it using client side scripting (jquery)
DataMember of yje Sensor name is "Instrument "which is a db table, and data member of sensor  type  is "InstrumentType"  which is  also a table.
For ddl1 i have populated it from instrument type , and for every selected  value of  instriument type in ddl1 , I need to populate the ddl2, the corressponding valuesfrom instrument,
but the point ihat i need to do it using client side scripting (jquery)
ASKER
Are u there?
OK. Â Here's my disconnect with you. Â The drop down controls in your designer page (<asp:DropDownList....) is a server-side control that is populated with data as the page is being prepared for rendering. Â Once the page is rendered, we are in the world of client-side.
So...before the page is "built" we have these two controls:
SENSOR NAME
               <asp:DropDownList ID="i_instrument" runat="server" DataMember="Instrument" DataTextField="name" DataValueField="id" AppendDataBoundItems="true " Width="160">
                  <asp:ListItem Text="" Value=""></asp:ListItem>
               </asp:DropDownList>
SENSOR TYPE
               <asp:DropDownList ID="i_instrumenttype" runat="server"  DataMember="InstrumentType " DataTextField="name" DataValueField="id" AppendDataBoundItems="true " Width="160" >
                 <asp:ListItem Text="" Value=""></asp:ListItem>
                </asp:DropDownList>
When the page is built, these two things are converted to HTML with values. Â How are the values for these drop downs getting populated when the details view is switched to Insert mode?
So...before the page is "built" we have these two controls:
SENSOR NAME
               <asp:DropDownList ID="i_instrument" runat="server" DataMember="Instrument" DataTextField="name" DataValueField="id" AppendDataBoundItems="true
                  <asp:ListItem Text="" Value=""></asp:ListItem>
               </asp:DropDownList>
SENSOR TYPE
               <asp:DropDownList ID="i_instrumenttype" runat="server"  DataMember="InstrumentType
                 <asp:ListItem Text="" Value=""></asp:ListItem>
                </asp:DropDownList>
When the page is built, these two things are converted to HTML with values. Â How are the values for these drop downs getting populated when the details view is switched to Insert mode?
ASKER
I populate  ddl in the DetailsView Data Bound event handler.
protected void DetailsView1_DataBound(object sender,EventArgds e)
{
-----------
----------
------------
if (DetailsView1.CurrentMode == DetailsViewMode.Insert)
{
DropDownList ddSType = (DropDownList)DetailsView1.FindControl("i_instrumenttype");
if (ddSType != null)
{
setupDdl(ddSType, dv3SensorType, sensor);
}
DropDownList ddlSName = (DropDownList)DetailsView1.FindControl("i_instrument");
if (ddlSName != null)
{
//setupDdl(ddlSName, dv3SensorName, sensor);
}
}
}
We're close now...what does setupDdl look like?
ASKER
if (ddl != null) // && ddl.Items.Count == 0
{
if (dv != null)
{
string sort = ddl.DataValueField;
if (!string.IsNullOrEmpty(sort) && dv.Table.Columns.Contains(sort)) dv.Sort = sort;
ddl.DataSource = dv;
ddl.DataBind();
}
if (!string.IsNullOrEmpty(selectedvalue))
{
ListItem li = null;
if (dv == null || ddl.Items.Count == 0)
{
li = new ListItem(selectedvalue);
ddl.Items.Add(li);
}
else li = ddl.Items.FindByValue(selectedvalue);
if (li != null) ddl.SelectedIndex = ddl.Items.IndexOf(li);
}
}
OK....so, where does dv come from?  Can you show me the WHOLE setupDdl  ?  The reason is, whatever logic you are applying in this method is what you will want in you Web Service.  That is, you will pass in your Instrument Type to the web service, it will produce the matching Instruments list, then in jquery we will take those values and reset the <select> element that's on the page.
ASKER
DataView dv = new DataView(instrument2, "", "name", DataViewRowState.CurrentRo ws);
      Â
DataView dv2 = new DataView(instrument3, "", "name", DataViewRowState.CurrentRo ws);
-------------------------- ---------- ---------- ---------- ---------- ------
dv is set in the DetailsView _Data Bound  method, before  (if(DetailsView1.CurrentMo de=Details ViewMode.I nser))
and is passed as a paramters to saetUpddl
setupDdl(DropDownList ddl, DataView dv, string selectedvalue)
      Â
DataView dv2 = new DataView(instrument3, "", "name", DataViewRowState.CurrentRo
--------------------------
dv is set in the DetailsView _Data Bound  method, before  (if(DetailsView1.CurrentMo
and is passed as a paramters to saetUpddl
setupDdl(DropDownList ddl, DataView dv, string selectedvalue)
Right. Â When you are rendering the Insert View, you are gathering data to populate the Instrument drop down based on (I'm guessing here) the first Instrument Type. Â
It's this logic that you want to put in to your web service. Â That is, your web service needs to return a dataset of Instrument Types based on a passed-in Instrument type.
It's this logic that you want to put in to your web service. Â That is, your web service needs to return a dataset of Instrument Types based on a passed-in Instrument type.
ASKER
yes you can say so
ASKER
web service needs to return a dataset of Instrument  based on a passed-in Instrument type.
Right.
ASKER
Are u there? Is solution ready?
You were going to create a Web Service that returns a data set containing Instruments based on a passed-in parameter of Instrument type. Â Once you have that, we can use Client Side jquery .get() method to retrieve that data and change the values of your Instrument select. Â So, I was waiting for you.
ASKER
I am  making  the web service,  you can tell me the next step how to retrieve the data  from web service using jquery
ASKER
Heylow are u there
I just need to ask how sohuld i call web service in my aspx page where the actual ddls are?
I just need to ask how sohuld i call web service in my aspx page where the actual ddls are?
You will use the kaiser method $.get().
Say your service is in the same folder as you aspx page, then you would call it like this:
$.get("myservice.asmx/Meth odName?id= " + id, function(){alert("it worked. Â You called your service")})
Of course, you will need to change the name of your service and the method in the service, and you will need to set the value of the id variable. Â Finally, the second part of the above call is called the callback function. Â For now, that is just an alert, but if you can get the call to work, Â I will walk you through processing the data you get back.
Say your service is in the same folder as you aspx page, then you would call it like this:
$.get("myservice.asmx/Meth
Of course, you will need to change the name of your service and the method in the service, and you will need to set the value of the id variable. Â Finally, the second part of the above call is called the callback function. Â For now, that is just an alert, but if you can get the call to work, Â I will walk you through processing the data you get back.
So...how are we doing with this?
If you want to get your list data from a service, you will want to use the .get() method in jquery, but the principals will be the same.
Open in new window