• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1703
  • Last Modified:

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)
0
Ammar Iqbal
Asked:
Ammar Iqbal
  • 19
  • 18
2 Solutions
 
Steve KrileCommented:
Here is a little code sample to handle all of this on the client side using Jquery.

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.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
    <title>Overlay Goodness</title>
    <script src="http://cdn.jquerytools.org/1.2.5/full/jquery.tools.min.js"></script>
    <style>
		html, body
		{

			font-family: Arial, Arial Unicode MS;
			font-size: .95em;
			height: 100%;
			width: 100%;
			border: 0;
			padding: 20px;
			margin: 0;
			font-weight:normal;
		}

    </style>
</head>
<body>

	<select id="departments"></select>
	<select id="jobs"></select>
	<script>
		var DDdata = [
		{
		"department": "IT",
		"jobs": [
		        {"title":"Programmer"},
		        {"title":"Solutions Architect"},
		        {"title":"Database Developer"}
		        ]
		},
		{"department": "Accounting",
		"jobs": [
			    {"title":"Accountant"},
			    {"title":"Payroll Officer"},
			    {"title":"Accounts Clerk"},
			    {"title":"Analyst"},
			    {"title":"Financial Controller"}
			    ]
		},
		{
		"department": "HR",
		"jobs": [
			    {"title":"Recruitment Consultant"},
			    {"title":"Change Management"},
			    {"title":"Industrial Relations"}
			    ]
		},
		{
		"department": "Marketing",
		"jobs": [
			    {"title":"Market Researcher"},
			    {"title":"Marketing Manager"},
			    {"title":"Marketing Co-ordinator"}
			    ]
		}
		]

		$(document).ready(function(){
			//set the first value to Select
			var options_departments = '<option>Select<\/option>';

			//loop through the data to create the departments in the select
			$.each(DDdata, function(i,d){
				options_departments += '<option value="' + d.department + '">' + d.department + '<\/option>';
			});

			//add the options to the departments dropdown
			$("select#departments", this).html(options_departments);

			//wire up a CHANGE function to the departments drop down
			$("select#departments", this).change(function(){
				//get the currently selected index
				var index = $(this).get(0).selectedIndex;

				//get the corresponding index in your JSON data
				var d = DDdata[index-1];  // -1 because index 0 is for empty 'Select' option

				//reset your options HTML for the Job menu
				var options = '';

				//provided the user has selecting something other than the first choice...
				if (index > 0) {
					//loop through the matching jobs list
					$.each(d.jobs, function(i,j){
								options += '<option value="' + j.title + '">' + j.title + '<\/option>';
					});
				} else {
					options += '<option>Select<\/option>';
				}
				$("select#jobs").html(options);
			})

		})
	</script>

</body>



</html>

Open in new window

0
 
Ammar IqbalAuthor Commented:
I need to get ddl list data from the database, and populate 2 with respect to the index change in ddl 1
0
 
Steve KrileCommented:
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.
var DDdata = []
$.getJSON("MyJSONService.ashx", function(data,textStatus){
  if(textStatus === "success" ) {
     DDData = data;
  }
})

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Ammar IqbalAuthor Commented:
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?
0
 
Steve KrileCommented:
Well, it just got complicated :)

I'm going to need to see your DetailsView template code.
0
 
Ammar IqbalAuthor Commented:
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.
<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>

Open in new window

0
 
Steve KrileCommented:
OK, this is going to get ugly.  What you want to do *can* be done.  

Let's take this step by step.

First, the easy stuff.  Let's get your drop down properly firing the change event.


In your template you need to add the following to your DropDown:

                                <asp:DropDownList ID="i_type" runat="server" onchange="changeDD(this)"  DataMember="EventType" DataTextField="name" DataValueField="id" AppendDataBoundItems="true" Width="160">
                                 <asp:ListItem Text="" Value=""></asp:ListItem>
                               </asp:DropDownList>



Make sure you have included jquery in your scripts for the page, then add this code somewhere below.




<script>

   function changeDD(dd) {
       alert($(dd).val());
   }

</script>



These three things:  Include Jquery, add onchange to the dropdown, and a changeDD function should now result in an alert telling you which value was selected.  Right?
0
 
Ammar IqbalAuthor Commented:
yes  iam getting an alert message , when i select some value from ddl1.  how to link this with the values in ddl2
0
 
Steve KrileCommented:
OK, next step...let's get that second Drop Down to react to this change.  We're still not going to play with live values yet.  I like to get the mechanics running first before I get to data manipulation.


Let's change the changeDD() function a bit to "talk" to the other dropdown.


function changeDD(dd) {
 
   //get the current index
   var selectedIndex = $(dd).val();

  //get the text of the current value
   var selectedText = $(":selected", $(dd)).text();

  //create a jquery object for the second drop down
  //this is a little jquery trick that allows you to find the drop down by ID even if asp.net has created a
  //really long id value for this select element (drop down)
  $dd2 = $("select[id$=i_instrument]");

  //remove all the values of the second drop down
  $("option",$dd2).remove();


  //add an option line to the second drop down matching what was selected from the first.  I know this isn't what
  //you want but we are just getting the two talking for now
  $dd2.append("<option value=\"" + selectedIndex + "\">" + selectedText + "</option>")

}





When you run this function by changing the dropdown, you should notice the value in the Sensor Name drop down changing.  Right?
0
 
Ammar IqbalAuthor Commented:
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
0
 
Steve KrileCommented:
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.
0
 
Ammar IqbalAuthor Commented:
no. I haven't created them before..
0
 
Steve KrileCommented:
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

0
 
Ammar IqbalAuthor Commented:
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
0
 
Steve KrileCommented:
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.
0
 
Ammar IqbalAuthor Commented:
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
0
 
Steve KrileCommented:
Right.  But client-side scripting needs the data.  That's where the service comes in.
0
 
Ammar IqbalAuthor Commented:
and the data is coming from the Database table (Instrument) in the drop down list "i_instrument"
0
 
Steve KrileCommented:
Um.  Wait.  What?  Can you show me the rendered HTML and the data you are talking about?
0
 
Ammar IqbalAuthor Commented:
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)
0
 
Ammar IqbalAuthor Commented:
Are u there?
0
 
Steve KrileCommented:
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?
0
 
Ammar IqbalAuthor Commented:
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);
  }
                    
            
 }



}

Open in new window

0
 
Steve KrileCommented:
We're close now...what does setupDdl look like?
0
 
Ammar IqbalAuthor Commented:

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);
                }
            }

Open in new window

0
 
Steve KrileCommented:
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.
0
 
Ammar IqbalAuthor Commented:
DataView dv = new DataView(instrument2, "", "name", DataViewRowState.CurrentRows);
             
DataView dv2 = new DataView(instrument3, "", "name", DataViewRowState.CurrentRows);

------------------------------------------------------------------------
dv is set in the DetailsView _Data Bound  method, before  (if(DetailsView1.CurrentMode=DetailsViewMode.Inser))

and is passed as a paramters to saetUpddl
setupDdl(DropDownList ddl, DataView dv, string selectedvalue)
0
 
Steve KrileCommented:
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.
0
 
Ammar IqbalAuthor Commented:
yes you can say so
0
 
Ammar IqbalAuthor Commented:
web service needs to return a dataset of Instrument  based on a passed-in Instrument type.
0
 
Steve KrileCommented:
Right.
0
 
Ammar IqbalAuthor Commented:
Are u there? Is solution ready?
0
 
Steve KrileCommented:
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.
0
 
Ammar IqbalAuthor Commented:
I am   making  the web service,  you can tell me the next step how to retrieve the data  from web service using jquery
0
 
Ammar IqbalAuthor Commented:
Heylow are u there
I just need to ask how sohuld i call web service in my aspx page where the actual ddls are?
0
 
Steve KrileCommented:
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/MethodName?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.
0
 
Steve KrileCommented:
So...how are we doing with this?
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

  • 19
  • 18
Tackle projects and never again get stuck behind a technical roadblock.
Join Now