Home > ASP.Net, Javascript, Jquery > Create a group with DropdownList using JQuery

Create a group with DropdownList using JQuery


Hi all,

try this example to Create a group with DropdownList using JQuery

1) Open VS2008 and create a new website and add web page

2) From Toolbox drag DropdownList control


<div>
 <asp:DropDownList ID="DropDownList1" runat="server" Width="200px"
 ondatabound="DropDownList1_DataBound">
 </asp:DropDownList>
 </div>

in code behind add the following code


protected void Page_Load(object sender, EventArgs e)
 {
 if (!IsPostBack)
 {
 DataTable table = new DataTable();
 table.Columns.Add("ID", typeof(int));
 table.Columns.Add("Number", typeof(int));
 //
 // Here we add five DataRows.
 //
 table.Rows.Add(1, 57);
 table.Rows.Add(2, 23);
 table.Rows.Add(3, 99);
 table.Rows.Add(4, 8);
 table.Rows.Add(5, 74);

DropDownList1.DataSource = table;
 DropDownList1.DataValueField = "ID";
 DropDownList1.DataTextField = "Number";

DropDownList1.DataBind();
 }
 }

protected void DropDownList1_DataBound(object sender, EventArgs e)
 {
 foreach (ListItem item in ((DropDownList)sender).Items)
 {
 if (System.Int32.Parse(item.Text) < 50)
 item.Attributes.Add("classification", "LessThanFifty");
 else
 item.Attributes.Add("classification", "GreaterThanFifty");
 }
 }

3) Add this Javascript code to create a group with DropdownList


<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
 <script type="text/javascript">
 $(document).ready(function() {
 //Create groups for dropdown list
 $("select#DropDownList1 option[classification='LessThanFifty']").wrapAll("<optgroup label='Less than fifty'>");
 $("select#DropDownList1 option[classification='GreaterThanFifty']").wrapAll("<optgroup label='Greater than fifty'>");
 });

 </script>
 <style>
 optgroup
 {
 background-color:Gray ;
 }
 </style>

Hope this helps

Good Luck

Advertisements
Categories: ASP.Net, Javascript, Jquery
  1. LTrane
    October 23, 2012 at 12:12 am

    This is great, but I am unable to get get this to work using an aspx page that uses a Master page.
    If I put the coding in a default page and apply a Master page the option group will not write to the default page. The drop down will populate, but the optiongroup does not write. This works
    just fine in a regular aspx page with no master page.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: