Click here to Skip to main content
11,647,828 members (61,169 online)
Click here to Skip to main content

JavaScript ListBox Control

, 24 Jul 2008 CPOL 227.5K 2.5K 127
Rate this:
Please Sign up or sign in to vote.
This article describes how to create a ListBox control using JavaScript.


JavaScript ListBoxControl is a cross-browser JavaScript class. It is a sub set of HTML selectelement with attribute size>= 2.


As you know, in the HTML ListBoxelement (selectelement 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 CheckBoxagainst each item of the ListBoxso that there was no need to press & hold Ctrl key while selecting multiple items. As HTML ListBoxdoes not support CheckBoxagainst each item, I've decided to develop my own custom ListBoxcontrol through JavaScript.


ListBoxControl has the following constructor:

ListBox(Arguments): The constructor of the ListBox classtakes an argumentof the type Object Literal. The definition of the argument Object Literalis given below:

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. 


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 Literalto null. In this case, each propertywill acquire its default value as:

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:

Property Default 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


ListBoxControl has the following publicmethods:

  • AddItem(Text, Value): Used to add a ListBoxItem. It takes two arguments:
    • Text: Item Text
    • Value: Item Value
  • GetItems(): Used to get collectionof all LBItem(ListBox Item)
  • GetItem(Index): Used to get a LBItem(ListBoxItem) at a given Itemindex. Returns nullin case Itemisn't found. It takes one argument:
    • Index: Item Index.
  • DeleteItems(): Used to delete all the ListBoxItems. Returns numbers of Items deleted
  • DeleteItem(Index): Used to delete a ListBoxItem at a given Item index. Returns trueon successful deletion, else false. It takes one argument:
    • Index: Item Index
  • GetTotalItems(): Used to get total number of ListBoxItems
  • Contains(Index): Used to check whether a ListBoxItem exists at a given Item index or not. Returns trueif Item exists, else false. It takes one argument:
    • Index: Item Index
  • Dispose(): Used to destroy ListBox Object

Note: The LBItemis an Object Literaland has the following definition:

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


ListBoxControl has only one property:

  • Version: Used to get the current version of the ListBoxControl


ListBoxControl has only one event:

  • Click: Fires when any one Item CheckBoxis clicked

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

var EventHandlerName = function(Sender, EventArgs) {}

Here Senderis the reference of the element (in this case the Item CheckBox) that raises the click event& EventArgsis a Object Literalthat contains necessary information regarding the event. EventArgs Object Literalhas the following definition:

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:

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

Create a divelement in the web page as:

<div id="base"></div>

Now create a scripttag in the headsection of the web page & put the following code in the window.onload eventas:

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


In the above code, first an argument Object Literalwith necessary properties has been created. After that ListBoxhas been instantiated using newkeyword. Finally different ListBoxItems have been added to the ListBox Object. Don't forget the click eventwire up in the argument Object Literalas:

ClickEventListener: OnClick

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

var OnClick = function(Sender, EventArgs)


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 clickon any one Item CheckBoxof the ListBoxcontrol.

Invoke the Disposemethod in the window.onunload eventin order to destroy ListBox Objectas:

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


So this is my approach to develop custom JavaScript ListBoxcontrol. Although it is only a subset of existing HTML ListBoxelement, 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 ListBoxcontrol.

Browser Compatibility

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



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


About the Author

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,.


You may also be interested in...

Comments and Discussions

GeneralVery nice article! One little bug.. Pin
Mark Giese9-May-10 17:52
memberMark Giese9-May-10 17:52 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150804.4 | Last Updated 25 Jul 2008
Article Copyright 2008 by Samir NIGAM
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid