Click here to Skip to main content
15,879,613 members
Articles / Web Development / HTML
Article

Editable Dropdown - DHTML Behavior

Rate me:
Please Sign up or sign in to vote.
3.26/5 (16 votes)
17 Oct 20043 min read 159.6K   2.3K   47   16
Allow users to add an item to a dropdown list.

Introduction

One of the most exciting new features introduced in Microsoft Internet Explorer 5 is Dynamic HTML (DHTML) Behaviors. DHTML Behaviors are components that encapsulate specific functionality or behavior on a page. There are two types of Behaviors; Element and Attached. In this article, I’ll be demonstrating Attached Behaviors, as these can be attached to ASP.NET WebControls.

The Dropdown List

For the purpose of this article, the Behavior will be attached to a standard HTML Select element but can be also attached to an ASP.NET DropDownList. The dropdown has an option with the value of -2 that will signal to the Behavior to change to a textbox.

HTML
<select name="Dropdown1" id="Dropdown1" class="FormDropdown" 
       onDropdownChange="alert('Dropdown has changed!');" 
       onDropdownRefresh="alert('Dropdown has been refreshed!');">
  <option value="-1" selected>Please Select...</option>
  <option value="1">Item1</option>
  <option value="2">Item2</option>
  <option value="3">Item3</option>
  <option value="4">Item4</option>
  <option value="5">Item5</option>
  <option value="-2">Other...</option>
</select>

There are two custom events, the “OnDropdownChange” event fires when the dropdown changes into a textbox, either by selecting the option with a value that matches with the “ChangeValue” property of the behavior or by calling the “Change” method. The other is the “OnDropdownRefresh” event, this fires when the textbox changes back to the dropdown; this can be by clicking the refresh icon or by calling the “Refresh” method.

Creating the Behavior

The Behavior itself isn’t written within the HTML document but in its own file with a .htc extension and is enclosed in <public:component> </public:component> tags. The first thing to do is add the declarations which include properties, events, and methods.

HTML
<public:component id="EditableDropdown" name="EditableDropdown" lightWeight="true" >

      <public:property     name="Version"          value="Editable Dropdown 1.0" />
      <public:property     name="ChangeValue"      value="-2" />
      <public:attach       event="ondocumentready" handler="Init" />
      <public:attach       event="onchange"        handler="Change" />
      <public:method       name="Refresh" /> 
      <public:method       name="Change" />
      <public:event        id="onDropdownChange"   name="ondropdownchange">
      <public:event        id="onDropdownRefresh"  name="ondropdownrefresh">

</public:component>

The Behavior runs its “Init” function when the document is ready, this function just checks that the Behavior is attached to a dropdown element.

JavaScript
function Init()
{
      // Check to see if attached to a dropdown list.
      if(!tagName.toLowerCase() == "select")
      {
            alert("Please attach to a dropdown list.");
            return;
      }
}

The “Change” function runs when the user changes the dropdown. In the “Change” function, we first check to see if the dropdown has already changed (this may be the case if the “Change” function is called from script), we then check to see if the value of the dropdown is the same as the “ChangeValue” property, which in this case is -2.

JavaScript
function Change()
{
      // Has the element already changed?
      if(changed) return;
      // Check to see if we need to change the dropdown list.
      if(value != ChangeValue)return;
      
      // Create the textbox that will replace the dropdown list.
      // The id and name are the same as the dropdowns with a "_txt" suffix.
      var txtElem = winDoc.createElement("<input type='text' id='"+ 
                    id +"_txt' name='" + name + 
                    "_txt' value='' class='FormTextbox' style='width:" 
                    + (style.width - 15) + "px'>");
      parentElement.appendChild(txtElem);
      
      // Create the refresh image and insert.
      var imgElem = winDoc.createElement("<img src='Refresh.gif'" + 
          " width='15' height='13' border='0' onclick='"+ id + 
          ".Refresh();') style='cursor:hand' id='"+ id +"_img'>");
      txtElem.parentElement.appendChild(imgElem);     
 
      // Hide the dropdown list and set the "changed" property to true.
      style.display = "none";
      changed = true;
 
      // Set the focus to the new textbox.
      txtElem.focus();
      
      // Fire the "onDropdownChange" event.
      onDropdownChange.fire(createEventObject());     
}

We then create a textbox with the same ID as the dropdown with a “_txt” suffix and a refresh icon. We then insert them next to the dropdown, hide the dropdown, and then fire the “OnDropdownChange” event.

Attaching the Behavior

Attaching the Behavior is as simple as adding a CSS style to the DropDownList. In the example, there is a class attached called “FormDropdown”.

HTML
.FormDropdown 
{
      font-family: Verdana, Arial, Helvetica, sans-serif;
      font-size: 11px;
      width: 150px;
      behavior:url(EditableDropdown.htc);
}

As you can see, we link the Behavior's HTC file with the CSS behavior attribute.

Using the Behavior

The Behavior creates a new element with a “_txt” suffix. Using ASP.NET, we can then look for the new element and insert it into a database. This code uses C# to check to see if the dropdown has a new value.

JavaScript
string newValue;
 
if(Request.Form["Dropdown1_txt"] != null)
    newValue = Request.Form["Dropdown1_txt"];

Considerations

While I was creating this Behavior, I had certain decisions to make, some of which I never had chance to try out or even think about deeply enough. The component works and does its job very well, but is far from being complete. Here are a list of things that might be worth considering if you want to improve the Behavior.

Renaming the dropdown and naming the textbox to the original name of the dropdown, using an Element Behavior instead of an attached Behavior, and maybe a ASP.NET server control as a wrapper.

Links and Resources

Demo

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
ambujs29-Mar-11 1:11
ambujs29-Mar-11 1:11 
GeneralNewly added item not showing in dropdownlist when refreshed- Pin
sheriefes21-Jun-08 19:46
sheriefes21-Jun-08 19:46 
Questionwill it work in VB code (asp.net)? Pin
sheriefes21-Jun-08 4:55
sheriefes21-Jun-08 4:55 
GeneralI NEED HELP!!! PLEASE Pin
habbit2k620-Sep-06 20:05
habbit2k620-Sep-06 20:05 
GeneralRe: I NEED HELP!!! PLEASE Pin
Ri Qen-Sin20-Sep-06 20:33
Ri Qen-Sin20-Sep-06 20:33 
GeneralIE GPF Pin
steveohara29-Oct-04 2:02
steveohara29-Oct-04 2:02 
GeneralRe: IE GPF Pin
stectaylor29-Oct-04 2:19
stectaylor29-Oct-04 2:19 
QuestionCross-Browser? Pin
Kelmen28-Oct-04 17:18
Kelmen28-Oct-04 17:18 
AnswerRe: Cross-Browser? Pin
stectaylor28-Oct-04 23:59
stectaylor28-Oct-04 23:59 
GeneralDoesnt Work With Multiple Instances Pin
VladCo23-Oct-04 2:27
VladCo23-Oct-04 2:27 
GeneralRe: Doesnt Work With Multiple Instances Pin
stectaylor24-Oct-04 0:20
stectaylor24-Oct-04 0:20 
GeneralProblem Persisting Change Pin
Shawn Bullock18-Oct-04 8:18
Shawn Bullock18-Oct-04 8:18 
GeneralRe: Problem Persisting Change Pin
stectaylor18-Oct-04 8:57
stectaylor18-Oct-04 8:57 
GeneralRe: Problem Persisting Change Pin
PeterK_22-Oct-04 4:10
PeterK_22-Oct-04 4:10 
It's a great idea for saving screen real-estate and creating a dynamic page without using postbacks. Thanks for bringing to our attention this often overlooked technique.

I was disappointed to see that the new value wasn't added to the dropdown in the demo. However, I see that someone has posted, on your blog, a way to dynamically update the dropdown without a postback. That is an important part of this.
GeneralRe: Problem Persisting Change Pin
stectaylor22-Oct-04 4:28
stectaylor22-Oct-04 4:28 
Generalawsome! Pin
impro18-Oct-04 5:28
impro18-Oct-04 5:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.