5,421,850 members and growing! (17,952 online)
Email Password   helpLost your password?
Web Development » Client side scripting » Controls     Intermediate License: The Code Project Open License (CPOL)

JavaScript ListBox Control

By SAMir Nigam

This article describes how to create a ListBox control using JavaScript.
C# (C# 2.0, C#), Javascript, CSS, HTML, XHTML, .NET (.NET, .NET 2.0), ASP.NET, Ajax, Dev

Posted: 25 Jun 2008
Updated: 24 Jul 2008
Views: 19,700
Bookmarked: 65 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
Prize winner in Competition "Best ASP.NET article of June 2008"
44 votes for this Article.
Popularity: 7.41 Rating: 4.51 out of 5
3 votes, 6.8%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
4 votes, 9.1%
4
37 votes, 84.1%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

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 process of selecting items. In a project client wanted a CheckBox against each item of the ListBox so that there were no need to press & hold Ctrl key while selecting the multiple items. As HTML ListBox does not support CheckBox against each item, so I’ve decided to develop my own custom ListBox control through JavaScript.

Constructor

ListBox Control has 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:

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 borderd color.
            ClickEventHandler: _ClickEventHandler // Reference of the click event handler. 
        };

Example:

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 asign each property of the argument Object Literal to null. In this case, each property will 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

Methods

ListBox Control has following public methods:

method.pngAddItem(Text, Value): Used to add an ListBox Item. It takes two arguments –

  • Text: Item Text.
  • Value: Item Value.

method.pngGetItems(): Used to get collection of all LBItem(ListBox Item).

method.pngGetItem(Index): Used to get a LBItem(ListBox Item) at a given Item index. Returns null in case of Item isn’t found. It takes one argument

  • Index: Item Index.

method.pngDeleteItems(): Used to delete all the ListBox Items. Returns numbers of Items deleted.

method.pngDeleteItem(Index): Used to delete a ListBox Item at a given Item index. Returns true on successfull deletion else false. It takes one argument

  • Index: Item Index.

method.pngGetTotalItems(): Used to get total no of ListBox Items.

method.pngContains(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.

method.pngDispose(): Used to destroy ListBox Object.

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

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:

property.pngVersion: Used to get the current version of the ListBox Control.

Event

ListBox Control has only one event:

event.pngClick: Fires when any one Item CheckBox is clicked.

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

 var EventHandlerName = function(Sender, EventArgs) {}

where 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 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 an div element in the web page as:

<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:

<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 key word. Finally deferent ListBox Items have been added to the ListBox Object. Don’t forget the click event wire up in the argument Object Literal as –

ClickEventListener: OnClick

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

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

Example:

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 gets 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:

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

Conclusion

So this is my approach to develop custom JavaScript ListBox control. Althoughit is only sub set of existing HTML ListBox element, but it is more user friendly than the existing. It can be further customize on deferent requirements. Please let me know bugs, errors & 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)

About the Author

SAMir Nigam


Currently I'm working as a Sr. Software Engineer in SRM Techsol Pvt. Ltd., Lucknow, INDIA. I possess following degrees:

  • MCA from U.P. Technical University, Lucknow, INDIA.
  • PGDCA from Institute of Engineering and Rural Technology, Allahabad, INDIA.
  • BSc from University of Allahabad, Allahabad, INDIA.


Award: Best ASP.NET article of June 2008: JavaScript ListBox Control

Occupation: Software Developer (Senior)
Company: STPL
Location: India India

Other popular Client side scripting articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 43 (Total in Forum: 43) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralThanks Again !!memberAbhijit Jana17:53 25 Aug '08  
GeneralCongratulation !!!memberAbhijit Jana23:00 24 Aug '08  
GeneralRe: Congratulation !!!memberSAMir Nigam23:28 24 Aug '08  
GeneralGreatmemberAarti Srivastava1:30 12 Aug '08  
GeneralRe: GreatmemberSAMir Nigam4:14 12 Aug '08  
GeneralCongratsmemberAnil Srivastava4:55 25 Jul '08  
GeneralRe: CongratsmemberSAMir Nigam20:07 25 Jul '08  
GeneralCongratulationmemberMS00823:27 24 Jul '08  
GeneralRe: CongratulationmemberSAMir Nigam23:28 24 Jul '08  
GeneralCongrats DEar Samirmemberlko.abhishek1:15 23 Jul '08  
GeneralRe: Congrats DEar SamirmemberSAMir Nigam1:27 23 Jul '08  
GeneralGreat job and here are some suggestions to make it even greatermemberGary Dryden6:11 22 Jul '08  
GeneralRe: Great job and here are some suggestions to make it even greatermemberSAMir Nigam1:29 23 Jul '08  
GeneralRe: Great job and here are some suggestions to make it even greatermemberGary Dryden3:32 23 Jul '08  
GeneralRe: Great job and here are some suggestions to make it even greatermemberSAMir Nigam3:38 23 Jul '08  
GeneralRe: Great job and here are some suggestions to make it even greatermemberGary Dryden3:42 23 Jul '08  
GeneralRe: Great job and here are some suggestions to make it even greatermemberSAMir Nigam3:45 23 Jul '08  
GeneralCongratulations for getting the First Prize For the ArticlememberSandeep Shekhar23:25 21 Jul '08  
GeneralRe: Congratulations for getting the First Prize For the ArticlememberSAMir Nigam0:23 22 Jul '08  
GeneralGood Jobmembersumeet197720:30 21 Jul '08  
GeneralRe: Good JobmemberSAMir Nigam20:57 21 Jul '08  
GeneralCongrats !!!memberashu fouzdar20:22 21 Jul '08  
GeneralRe: Congrats !!!memberSAMir Nigam20:58 21 Jul '08  
GeneralGreat samirmemberMCSDvikasmisra19:36 21 Jul '08  
GeneralRe: Great samirmemberSAMir Nigam20:58 21 Jul '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jul 2008
Editor:
Copyright 2008 by SAMir Nigam
Everything else Copyright © CodeProject, 1999-2008
Web16 | Advertise on the Code Project