Click here to Skip to main content
Email Password   helpLost your password?
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:

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:

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:

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 the following public methods:

Note: The LBItem is an Object Literal and 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:

Event

ListBox Control has only one event:

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

 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:

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

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

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
You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralJSP
pandajericho
7:30 26 Oct '08  
Hi, are you able to give me some directions if i'm trying to do this in jsp? I love this js you created, but i having trouble using this for it's in .net platform.

Are you able to show me how it should be in jsp? Many thanks!
GeneralGeneral Query
Abhijit Jana
19:26 22 Oct '08  
Hi Samir,
can you please tell me that how did you create the animated gif? are you using any tool ?

Thanks in advance !!!

cheers,
Abhijit

GeneralRe: General Query
Sameer NIGAM
20:01 22 Oct '08  
I'm using a tool.

Samir NIGAM
My Articles

GeneralRe: General Query
Abhijit Jana
20:43 23 Oct '08  
Hi samir, thanks for your response. can you please tell me the name of that tool ?
Check my this article,
My Recent Artilce[^]
I am create this gif by writting C# code OMG and its not prominant

cheers,
Abhijit

GeneralMultiple contols on a page
bjmbrown
6:11 29 Sep '08  
Thank you for this article. It is very helpful. I would like to use this control inside a asp.net web user control. I would be very grateful if you could provide some direction as to the changes that would need to occur in order for the javascript to handle each instance of the control.

Thank you.

Bruce Browning

GeneralRe: Multiple contols on a page
Sameer NIGAM
19:03 29 Sep '08  
thanks bjmbrown. simply pass reference of the base object to the Argument Object Literal. e.g. if you want to display this ListBox inside a Panel (id="pnlBase")Control pass its reference as

var Arguments = {
Base: document.getElementById('<%= pnlBase.ClientId %>'),
Rows: 6,
...
};


Samir NIGAM
My Articles

GeneralHow can we check all the items on a button click
shahu
0:36 29 Sep '08  
How to provide a button that will check and uncheck all the items together
GeneralRe: How can we check all the items on a button click
Sameer NIGAM
19:05 29 Sep '08  
Hi Shahu. you have to modify ListBox class code accoding to your requirement.

Samir NIGAM
My Articles

GeneralHow to do Drag and Drop in single listbox through javaScript
Achyutanand Nayak
22:19 28 Sep '08  
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.
GeneralRe: How to do Drag and Drop in single listbox through javaScript
Sameer NIGAM
19:09 29 Sep '08  
Hi Achyutanand. Currently ListBox doesn't support drag & drop functionality.

Samir NIGAM
My Articles

GeneralRe: How to do Drag and Drop in single listbox through javaScript
Achyutanand Nayak
19:50 2 Oct '08  
But Sir some website is telling u can do using OLE ,WAF something. But
i don't now this thing also.
GeneralHow can this support DB load?? [modified]
JLKEngine008
19:27 17 Sep '08  
Also please tell me how do i submit this element to an ASP page coz i have already created the page with this element cobining it with ASP script that fetches data from DB.


Can you provide js+ajax get the result ,then band the result to the ListBox?? that is you can use ajax to get data from db , and through client js to get the datasource, the datasource is XML , or Array or
string Value, etc.


and I suggest you can provide this, so ,it may strong!! you can contact me by e-mail or MSN

MSN: JLKEngine@hotmail.com
e-mail: hy2001al@163.com

http://www.linjon.cn 成都领君科技有限公司 China

modified on Wednesday, September 24, 2008 1:01 AM

GeneralRe: How can this support DB load??
Sameer NIGAM
19:35 29 Sep '08  
first of all I've no idea about ASP. you can use XMLHttpRequest object to get results form the any data source. It isn't a functionality related to it. you can find lots of very good article on the codeproject.com regaridng XMLHttpRequest object.

Samir NIGAM
My Articles

GeneralOne more thing Please help fast
Bhatt Saurabh
5:11 11 Sep '08  
Also please tell me how do i submit this element to an ASP page coz i have already created the page with this element cobining it with ASP script that fetches data from DB.

Please tell fast coz i am unable to find answer.

Thank you

web programmer

GeneralRe: One more thing Please help fast
Sameer NIGAM
19:32 29 Sep '08  
I've no idea about ASP script.

Samir NIGAM
My Articles

QuestionGreat Job but one query
Bhatt Saurabh
3:08 11 Sep '08  
Dear friend,
I have been succefully able to apply this to my needful but i have one query. It is that can I make this into a a Select type Drop box i.e. kind of combo box. If yes how????


Please tell me the needfull

Thank you

Just another IT guy next door

AnswerRe: Great Job but one query
Sameer NIGAM
19:31 29 Sep '08  
Hi Saurabh. Actually i've developed it according to my client's need. you can do anything you want.

Samir NIGAM
My Articles

GeneralMulti-column functionality??
JLKEngine008
18:56 1 Sep '08  
cau you give me a demo?
thanks a lot! hy2001al@163.com
GeneralRe: Multi-column functionality??
Sameer NIGAM
19:23 29 Sep '08  
I've already answered about multi column functionality.

Samir NIGAM
My Articles

Generalcan you suopport multi cols?
JLKEngine008
18:05 1 Sep '08  
How to set multi cols to the listBox ?
GeneralRe: can you suopport multi cols?
Sameer NIGAM
19:21 29 Sep '08  
currently ListBox control doesn't support multi columns but you can modify the code according to youe requirements.

Samir NIGAM
My Articles

Generalhow can I load data?
JLKEngine008
18:04 1 Sep '08  
how can I load datasource , such as DataTable or DataSet or XML Data?
GeneralRe: how can I load data?
Sameer NIGAM
19:20 29 Sep '08  
you can use an AJAX call in window.onload event to get result from the any data source & after that parse this result and add items using oListBox.AddItem method.

Samir NIGAM
My Articles

GeneralThanks Again !!
Abhijit Jana
17:53 25 Aug '08  
Hi Samir,
This again helped me a lot to solve out my problem !!!

Thanks again !!!


GeneralRe: Thanks Again !!
Sameer NIGAM
19:15 29 Sep '08  
you are welcome.

Samir NIGAM
My Articles


Last Updated 25 Jul 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010