Click here to Skip to main content
15,860,972 members
Articles / Web Development / XHTML

JavaScript ListBox Control

Rate me:
Please Sign up or sign in to vote.
4.80/5 (56 votes)
24 Jul 2008CPOL3 min read 473.7K   3.2K   130   72
This article describes how to create a ListBox control using JavaScript.
preview.gif

Introduction

JavaScript ListBox Control is a cross-browser JavaScript class. It is a sub set of HTML select element with attribute size >= 2.

Background

As you know, in the HTML ListBox element (select element with attribute size >=2), if you want to select multiple items, then you have to press & hold the Ctrl key during the process of selecting items. In a project, a client wanted a CheckBox against each item of the ListBox so that there was no need to press & hold Ctrl key while selecting multiple items. As HTML ListBox does not support CheckBox against each item, I've decided to develop my own custom ListBox control through JavaScript.

Constructor

ListBox Control has the following constructor:

ListBox(Arguments): The constructor of the ListBox class takes an argument of the type Object Literal. The definition of the argument Object Literal is given below:

JavaScript
var Arguments = {
      Base: _Base, //Base reference where ListBox to be displayed.
      Rows: _Rows, //No. of visible items.
      Width: _Width, // Width of the ListBox.
      NormalItemColor: _NormalItemColor, // Normal item color.
      NormalItemBackColor: _NormalItemBackColor, // Normal item back color.
      AlternateItemColor: _AlternateItemColor, // Alternate item color.
      AlternateItemBackColor: _AlternateItemBackColor, // Alternate item back color.
      SelectedItemColor: _SelectedItemColor, // Selected item color.
      SelectedIItemBackColor: _SelectedIItemBackColor, // SelectedI item back color.
      HoverItemColor: _HoverItemColor, // Hover item color.
      HoverItemBackColor: _HoverItemBackColor, // Hover item back color.
      HoverBorderdColor: _HoverBorderdColor, // Hover bordered color.
      ClickEventHandler: _ClickEventHandler // Reference of the click event handler. 
 };

Example:

JavaScript
var Arguments = {
            Base: document.getElementById('base'),
            Rows: 6,
            Width: 300,
            NormalItemColor: 'Black',
            NormalItemBackColor: '#ffffff',
            AlternateItemColor: 'Black',
            AlternateItemBackColor: '#E0E0E0',
            SelectedItemColor: '#ffffff',
            SelectedIItemBackColor: '#E6A301',
            HoverItemColor: '#ffffff',
            HoverItemBackColor: '#2259D7',
            HoverBorderdColor: 'orange',
            ClickEventHandler: CheckBoxOnClick
        };

You can assign each property of the argument Object Literal to null. In this case, each property will acquire its default value as:

JavaScript
var Arguments = {
            Base: null,
            Rows: null,
            Width: null,
            NormalItemColor: null,
            NormalItemBackColor: null,
            AlternateItemColor: null,
            AlternateItemBackColor: null,
            SelectedItemColor: null,
            SelectedIItemBackColor: null,
            HoverItemColor: null,
            HoverItemBackColor: null,
            HoverBorderdColor: null,
            ClickEventHandler: null
        };

Properties & their default values have been tabulated below:

PropertyDefault Value
Base document.documentElement
Rows 6
Width 300
NormalItemColor 'Black'
NormalItemBackColor '#ffffff'
AlternateItemColor 'Black'
AlternateItemBackColor '#E0E0E0'
SelectedItemColor '#ffffff'
SelectedIItemBackColor '#E6A301'
HoverItemColor '#ffffff'
HoverItemBackColor '#2259D7'
HoverBorderdColor 'orange'
ClickEventHandler Anonymous method

Methods

ListBox Control has the following public methods:

  • AddItem(Text, Value): Used to add a ListBox Item. It takes two arguments:
    • Text: Item Text
    • Value: Item Value
  • GetItems(): Used to get collection of all LBItem(ListBox Item)
  • GetItem(Index): Used to get a LBItem(ListBox Item) at a given Item index. Returns null in case Item isn't found. It takes one argument:
    • Index: Item Index.
  • DeleteItems(): Used to delete all the ListBox Items. Returns numbers of Items deleted
  • DeleteItem(Index): Used to delete a ListBox Item at a given Item index. Returns true on successful deletion, else false. It takes one argument:
    • Index: Item Index
  • GetTotalItems(): Used to get total number of ListBox Items
  • Contains(Index): Used to check whether a ListBox Item exists at a given Item index or not. Returns true if Item exists, else false. It takes one argument:
    • Index: Item Index
  • Dispose(): Used to destroy ListBox Object

Note: The LBItem is an Object Literal and has the following definition:

JavaScript
var LBItem = {
   IsSelected: _IsSelected, // true/false.
   Text: _Text, // Item Text.
   Value: _Value, // Item Value.
   ItemIndex: _ItemIndex // Item Index.
}; 

Property

ListBox Control has only one property:

  • Version: Used to get the current version of the ListBox Control

Event

ListBox Control has only one event:

  • Click: Fires when any one Item CheckBox is clicked

The local anonymous method that responds to the click event (i.e. event handler) has the following signature:

JavaScript
var EventHandlerName = function(Sender, EventArgs) {}

Here Sender is the reference of the element (in this case the Item CheckBox) that raises the click event & EventArgs is a Object Literal that contains necessary information regarding the event. EventArgs Object Literal has the following definition:

JavaScript
var EventArgs = {
    Text: _Text, // Item Text.
    Value: _Value, // Item Value.
    ItemIndex: _ItemIndex // Item Index.
}; 

Using the Control

Add the reference of the ListBox.js file in your web page as:

ASP.NET
<script type="text/javascript" src="JS/ ListBox.js"></script>

Create a div element in the web page as:

ASP.NET
<div id="base"></div>

Now create a script tag in the head section of the web page & put the following code in the window.onload event as:

JavaScript
<script type="text/javascript">
    var oListBox;
    window.onload = function()
    {        
        var Arguments = {
            Base: document.getElementById('base'),
            Rows: 3,
            Width: 300,
            NormalItemColor: null,
            NormalItemBackColor: null,
            AlternateItemColor: null,
            AlternateItemBackColor: null,
            SelectedItemColor: null,
            SelectedIItemBackColor: null,
            HoverItemColor: null,
            HoverItemBackColor: null,
            HoverBorderdColor: null,
            ClickEventHandler: OnClick
        };
        
        oListBox = new ListBox(Arguments); 

        oListBox.AddItem('CodeProject.com','http://www.codeproject.com');
        oListBox.AddItem('yahoo.com','http://www.yahoo.com/');
        oListBox.AddItem
		('microsoft.com','http://www.microsoft.com/en/us/default.aspx');
        oListBox.AddItem('asp.net','http://www.asp.net');
        oListBox.AddItem('cricinfo.com','http://www.cricinfo.com/');
        oListBox.AddItem('AOL','http://www.aol.com/');
        oListBox.AddItem('STPL','http://stpl.biz');
    }
</script>

In the above code, first an argument Object Literal with necessary properties has been created. After that ListBox has been instantiated using new keyword. Finally different ListBox Items have been added to the ListBox Object. Don't forget the click event wire up in the argument Object Literal as:

JavaScript
ClickEventListener: OnClick

Where OnClick is the reference of the click event handler which is created as a local anonymous method:

JavaScript
var OnClick = function(Sender, EventArgs)
{
    //Code 
} 

Example:

JavaScript
var OnClick = function(Sender, EventArgs)
{
    var Message = new Array();

    Message.push('IsSelected: ' + Sender.checked.toString());
    Message.push('Text: ' + EventArgs.Text);
    Message.push('Value: ' + EventArgs.Value);
    Message.push('Index: ' + EventArgs.ItemIndex);

    document.getElementById('DivMessage').innerHTML = Message.join('<br />');
}

This method will get called when you will click on any one Item CheckBox of the ListBox control.

Invoke the Dispose method in the window.onunload event in order to destroy ListBox Object as:

JavaScript
window.onunload = function(){oListBox.Dispose(); }

Conclusion

So this is my approach to develop custom JavaScript ListBox control. Although it is only a subset of existing HTML ListBox element, it is more user friendly than the existing one. It can be further customized for different requirements. Please let me know about bugs and/or errors & give suggestions to improve this ListBox control.

Browser Compatibility

I have tested this control on a number of web browsers.

Browsers.png

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead Infogain India Pvt Ltd
India India


Samir NIGAM is a Microsoft Certified Professional. He is an insightful IT professional with results-driven comprehensive technical skill having rich, hands-on work experience n web-based applications using ASP.NET, C#, AJAX, Web Service, WCF, jQuery, Microsoft Enterprise Library , LINQ, MS Entity Framework, nHibernate, MS SQL Server & SSRS.



He has earned his master degree (MCA) from U.P. Technical University, Lucknow, INDIA, his post graduate dipoma (PGDCA ) from Institute of Engineering and Rural Technology, Allahabad, INDIA and his bachelor degree (BSc - Mathematics) from University of Allahabad, Allahabad, INDIA.



He has good knowledge of Object Oriented Programming, n-Tier Architecture, SOLID Principle, and Algorithm Analysis & Design as well as good command over cross-browser client side programming using JavaScript & jQuery,.



Awards:



Comments and Discussions

 
QuestionThis ListBox is awesome, but one question Pin
Member 1502827028-Jan-21 13:41
Member 1502827028-Jan-21 13:41 
Questionhow will you populate it from database Pin
sairfan15-Jan-12 19:01
sairfan15-Jan-12 19:01 
GeneralVery nice article! One little bug.. Pin
Mark Giese9-May-10 17:52
Mark Giese9-May-10 17:52 
GeneralJSP Pin
pandajericho26-Oct-08 6:30
pandajericho26-Oct-08 6:30 
GeneralGeneral Query Pin
Abhijit Jana22-Oct-08 18:26
professionalAbhijit Jana22-Oct-08 18:26 
GeneralRe: General Query Pin
Samir NIGAM22-Oct-08 19:01
Samir NIGAM22-Oct-08 19:01 
GeneralRe: General Query Pin
Abhijit Jana23-Oct-08 19:43
professionalAbhijit Jana23-Oct-08 19:43 
GeneralMultiple contols on a page Pin
bjmbrown29-Sep-08 5:11
bjmbrown29-Sep-08 5:11 
GeneralRe: Multiple contols on a page Pin
Samir NIGAM29-Sep-08 18:03
Samir NIGAM29-Sep-08 18:03 
QuestionHow can we check all the items on a button click Pin
shahu28-Sep-08 23:36
shahu28-Sep-08 23:36 
AnswerRe: How can we check all the items on a button click Pin
Samir NIGAM29-Sep-08 18:05
Samir NIGAM29-Sep-08 18:05 
QuestionHow to do Drag and Drop in single listbox through javaScript Pin
Achyutanand Nayak28-Sep-08 21:19
Achyutanand Nayak28-Sep-08 21:19 
Hi friend

I am having single listbox its contain some data like(one,two,three,four), i want
to drag and drop action in listbox.

Example:-
first time it’s looks like this

one
two
three
four

if i drag one to four (after drag and drop action) it’ll display

two
three
four
one

if again i drag three to four (after drag and drop action) it’ll display

two
four
three
one

Please help me it’s urgent and if possible send me some code in my email ID (achyutanand@gmail.com) or here only.
AnswerRe: How to do Drag and Drop in single listbox through javaScript Pin
Samir NIGAM29-Sep-08 18:09
Samir NIGAM29-Sep-08 18:09 
GeneralRe: How to do Drag and Drop in single listbox through javaScript Pin
Achyutanand Nayak2-Oct-08 18:50
Achyutanand Nayak2-Oct-08 18:50 
QuestionHow can this support DB load?? [modified] Pin
JLKEngine00817-Sep-08 18:27
JLKEngine00817-Sep-08 18:27 
AnswerRe: How can this support DB load?? Pin
Samir NIGAM29-Sep-08 18:35
Samir NIGAM29-Sep-08 18:35 
GeneralOne more thing Please help fast Pin
Bhatt Saurabh11-Sep-08 4:11
Bhatt Saurabh11-Sep-08 4:11 
GeneralRe: One more thing Please help fast Pin
Samir NIGAM29-Sep-08 18:32
Samir NIGAM29-Sep-08 18:32 
QuestionGreat Job but one query Pin
Bhatt Saurabh11-Sep-08 2:08
Bhatt Saurabh11-Sep-08 2:08 
AnswerRe: Great Job but one query Pin
Samir NIGAM29-Sep-08 18:31
Samir NIGAM29-Sep-08 18:31 
QuestionMulti-column functionality?? Pin
JLKEngine0081-Sep-08 17:56
JLKEngine0081-Sep-08 17:56 
AnswerRe: Multi-column functionality?? Pin
Samir NIGAM29-Sep-08 18:23
Samir NIGAM29-Sep-08 18:23 
Questioncan you suopport multi cols? Pin
JLKEngine0081-Sep-08 17:05
JLKEngine0081-Sep-08 17:05 
AnswerRe: can you suopport multi cols? Pin
Samir NIGAM29-Sep-08 18:21
Samir NIGAM29-Sep-08 18:21 
Questionhow can I load data? Pin
JLKEngine0081-Sep-08 17:04
JLKEngine0081-Sep-08 17:04 

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.