Listbox

This element is used to create a list of items. This is a simpler version of a tree. Nested rows are not supported, but a listbox may contain multiple columns. There are numerous methods which allow the items in the listbox to be retrieved and modified.

You may specify the number of rows to display in the list using the rows attribute. Additional rows can be viewed by using a scroll bar. All of the rows in the listbox are the same height, which is the height of the largest item in the list. If you are using Mozilla 1.8 (Firefox 1.5) or later and wish to create a list with non-text content, you might consider using the richlistbox element instead.

More information about listbox

Example:

    <listbox id="theList">
      <listitem label="Ruby"/>
      <listitem label="Emerald"/>
      <listitem label="Sapphire"/>
      <listitem label="Diamond"/>
    </listbox>

The listbox element implements the following interfaces:

nsIAccessibleProvider   nsIDOMXULMultiSelectControlElement  

Attributes:

disableKeyNavigation disabled preference rows seltype
suppressonselect tabindex value

Properties and Methods:

accessible addItemToSelection appendItem clearSelection currentItem
disableKeyNavigation disabled ensureElementIsVisible ensureIndexIsVisible getIndexOfFirstVisibleRow
getIndexOfItem getItemAtIndex getNextItem getNumberOfVisibleRows getPreviousItem
getRowCount getSelectedItem insertItemAt invertSelection listBoxObject
removeItemAt removeItemFromSelection scrollToIndex selType selectAll
selectItem selectItemRange selectedCount selectedIndex selectedItem
selectedItems tabIndex timedSelect toggleItemSelection value

Attributes:

Inherited from XUL Element:

align
allowevents
allownegativeassertions
class
coalesceduplicatearcs
collapsed
container
containment
context
contextmenu
datasources
dir
empty
equalsize
flags
flex
height
hidden
id
insertafter
insertbefore
left
maxheight
maxwidth
menu
minheight
minwidth
mousethrough
observes
ordinal
orient
pack
persist
popup
position
preference-editable
ref
removeelement
sortDirection
sortResource
sortResource2
statustext
style
template
tooltip
tooltiptext
top
uri
wait-cursor
width

disableKeyNavigation

Type: boolean

If this attribute is not used, the user can navigate to specific items in the list by pressing the first the first letter of the item's label. This is done incrementally, so pressing additional keys will select more specific items. This feature may be disabled for a listbox by setting this attribute to true.

disabled

Type: boolean

Indicates whether the listbox is disabled or not. If this attribute is set to true, the listbox is disabled. This is usually drawn with the text in grey. If the listbox is disabled, it does not respond to user actions. The element cannot be focused and the command event will not fire. The element will still respond to mouse events. To enable the listbox, leave the attribute out entirely as opposed to setting the value to false.

preference    Mozilla 1.8

Type: element id

Connects the listbox to a corresponding preference. This attribute only has any effect when used inside a prefwindow. The value of the preference will be updated to match the value property of the listbox.

rows

Type: integer

The number of rows to display in the list box. If the listbox contains more than this many rows, a scrollbar will appear which the user can use to scroll to the other rows. To get the actual number of rows in the listbox, use the getRowCount method.

seltype

Type: one of the values below

Used to indicate whether multiple selection is allowed.

suppressonselect

Type: boolean

If this attribue is not specified, a select event is fired whenever an item is selected, either by the user or by calling one of the select methods. If set to true, the select event is never fired.

tabindex

Type: integer

The tab order of the element. The tab order is the order in which the focus is moved when the user presses the Tab key. Elements with a higher tabindex are later in the tab order sequence.

value

Type: string

You can associate a data value with each listitem. It is not used for any specific purpose but you can access it with a script for your own use.


Properties and Methods:

Inherited from XUL Element:

align
allowEvents
blur
boxObject
boxObject.element
boxObject.getLookAndFeelMetric
boxObject.height
boxObject.screenX
boxObject.screenY
boxObject.width
boxObject.x
boxObject.y
builder
className
click
collapsed
contextMenu
controllers
database
datasources
dir
doCommand
flex
focus
getElementsByAttribute
height
hidden
id
left
maxHeight
maxWidth
menu
minHeight
minWidth
observes
ordinal
orient
pack
persist
ref
resource
statusText
style
tooltip
tooltipText
top
width

Inherited from Element:

addEventListener
appendChild
attributes
childNodes
cloneNode
dispatchEvent
firstChild
getAttribute
getAttributeNS
getAttributeNode
getAttributeNodeNS
getElementsByTagName
getElementsByTagNameNS
hasAttribute
hasAttributeNS
hasAttributes
hasChildNodes
insertBefore
isSupported
lastChild
localName
namespaceURI
nextSibling
nodeName
nodeType
nodeValue
normalize
ownerDocument
parentNode
prefix
previousSibling
removeAttribute
removeAttributeNS
removeAttributeNode
removeChild
removeEventListener
replaceChild
setAttribute
setAttributeNS
setAttributeNode
setAttributeNodeNS
tagName

accessible

Type: nsIAccessible

Returns the accessibility object for the listbox.

addItemToSelection ( item )

Return Type: no return value

Selects the given item, without deselecting any other items that are already selected.

appendItem ( label , value )

Return Type: listitem element

Creates a new listitem element and adds it to the end of the list box. You may optionally set a value. The function returns the new item.

clearSelection ( )

Return Type: no return value

Deselects all of the items.

currentItem

Type: listitem element

Returns the last selected item in the list box, which is only useful in a multiple selection list box.

disableKeyNavigation

Type: boolean

If this attribute is not used, the user can navigate to specific items in the list by pressing the first the first letter of the item's label. This is done incrementally, so pressing additional keys will select more specific items. This feature may be disabled for a listbox by setting this attribute to true.

disabled

Type: boolean

Gets and sets the value of the disabled attribute.

ensureElementIsVisible ( element )

Return Type: no return value

If the element in the list box is not currently visible to the user, the list box view is scrolled so that it is. If the item is already visible, no scrolling occurs.

ensureIndexIsVisible ( index )

Return Type: no return value

If the item at the specified index is not currently visible to the user, the list box view is scrolled so that it is. If the item is already visible, no scrolling occurs.

getIndexOfFirstVisibleRow ( )

Return Type: integer

Returns the index of the first displayed row in the list box. This is not the same as the first row. If the view of the list box has been scrolled down, the function can be used to retrieve the index of the first row that the user can see.

getIndexOfItem ( item )

Return Type: integer

Returns the zero-based position of the given item. Items are numbered starting from the first item displayed in the list.

getItemAtIndex ( index )

Return Type: listitem element

Returns the item that is at the position specified by the parameter index in the list box.

getNextItem ( startItem, delta )

Return Type: listitem element

This method returns a item after another one. The parameter startItem is the item and delta is the number of items to count to.

getNextItem ( someItem, 2 );

This example, given a item someItem, will return the item 2 rows after it, or null if no such item exists.

getNumberOfVisibleRows ( )

Return Type: integer

Returns the number of rows of the list box that are currently visible to the user.

getPreviousItem ( startItem, delta )

Return Type: listitem element

This method returns a item before another one. The parameter startItem is the item and delta is the number of items to count to.

getPreviousItem ( someItem, 5 );

This example, given a item someItem, will return the item 5 rows before it, or null if no such item exists.

getRowCount ( )

Return Type: integer

Returns the total number of rows in the list box, regardless of how many rows are displayed.

getSelectedItem ( index )

Return Type: listitem element

When multiple items are selected, you can retrieve each selected item using this function. The argument index specifies the index in the list of selected items, not the row number of the item. Thus, getSelectedItem(7) will return the seventh selected item.

insertItemAt ( index, label , value )

Return Type: listitem element

Creates a new listitem element and inserts it at a specific position in the list box. You may optionally set a value. The function returns the new item.

invertSelection ( )

Return Type: no return value

Reverses the selected state of all the items. Selected items become deselected and deselected items become selected.

listBoxObject

Type: nsIListBoxObject

The nsIListBoxObject behind the list box. This property is read-only. Most of the features of the list box object are already available directly in the listbox, so you will rarely have need to use this box object directly.

removeItemAt ( index )

Return Type: listitem element

Removes the child item in the list box at the given index. The function returns the removed item.

removeItemFromSelection ( item )

Return Type: no return value

Deselects the given item without deselecting other items.

scrollToIndex ( index )

Return Type: no return value

Scrolls the list box view to the specified index. This is different than ensureIndexIsVisible because the view is always scrolled.

selType

Gets and sets the value of the seltype attribute.

selectAll ( )

Return Type: no return value

Selects all of the items. A select event is sent after the selection is made.

selectItem ( item )

Return Type: no return value

Deselects all of the currently selected items and selects the given item. A select event is sent after the selection is made.

selectItemRange ( startItem , endItem )

Return Type: no return value

Selects the items in-between two items given as arguments, including the start and end items. All other items are deselected. This method does nothing for single-selection list boxes. A select event is sent after the selection is made.

selectedCount

Type: integer

Returns the number of items that are currently selected.

selectedIndex

Type: integer

Returns the index of the currently selected item. You may select an item by assigning its index to this property. By assigning -1 to this property, all items will be deselected.

selectedItem

Type: listitem element

Returns the currently selected item. If there are multiple items selected, the property will hold only the first selected item. To get all of the selected items, use the selectedItems property. You may select an item by assigning a listitem element to this property. All other items will be deselected.

selectedItems

Type: array of listitems

Returns an array of the selected items in the list.

tabIndex    Mozilla 1.8

Type: integer

Get and sets the value of the tabindex attribute.

timedSelect ( item , timeout )

Return Type: no return value

Selects the item specified by the argument item after the number of milliseconds given by the timeout argument. All other items are deselected.

toggleItemSelection ( item )

Return Type: no return value

If the specified item is selected, it is deselected. If it is not selected, it is selected. Other items in the list box that are selected are not affected, and retain their selected state.

value

Type: string

Gets and sets the value of the value attribute.

Add a note User Contributed Notes
November 30, 2005, 8:33 am amb_ff at yahoo dot com
When I tried to look for a way to get a specific cell value in a multi-columns list, there seems to be none. So I came up with this function, guess it might be helpful to others:

function getListCellVal(listboxId, numCols, whichCol) {
var listbox = document.getElementById(listboxId);
var listcell = document.getElementsByTagName("listcell");
var index = (listbox.selectedIndex * numCols) + whichCol;
var val = listcell[index].getAttribute("label");

return val;
}

Input:
- listboxId: the id of your listbox
- numCols: the number of columns in your multi-column list
- whichCol: the column where you want to get the value, starting at 0
Output:
the value of the cell in the column you specified in whichCol of the current selected listitem.
October 24, 2005, 9:18 am malvim at gbl dot com dot br
Ok, all these methods for clearing the contents really donīt work if you have <listhead> or <listcols> elements in your list. This is because of the bug mentioned below, and, as the guys at Mozilla state on the bug page, it will not be fixed until next releases of FireFox (later than 1.0.x).

So, I came up with a workaround solution that will work, even after the bug is fixed, I think. It manipulates the document directly via the DOM, not relying on the behavior of the removeItemAt method, which has the bug. Getting the 'listitem' children nodes under list make the code remove only the <lititem> elements, and not the other ones, like your listīs header, or column definition.

This is it:
---------------------------------
function clearList(list) {
var items = list.getElementsByTagName('listitem');
while(items.length > 0) {
list.removeChild(items[0]);
}
}
---------------------------------

Hope you find it useful.
Marcelo Alvim.
September 7, 2005, 9:06 pm lzlhero at 163 dot com
These previous post functions for remove all items in listbox have some little bugs. I fixed them, and post again. Hope you like it.


function removeAllItems( strListBox )
{
var oListBox = document.getElementById(strListBox);
var rowCount = oListBox.getRowCount();

for( var i = 0; i < rowCount; i++ )
{
oListBox.removeItemAt(0);
}
}
August 15, 2005, 9:52 am webmaster at m-bread dot com
Setting disabled to true only seems to have partial affect on my browser (Firefox 1.0.6 on Win98). The items are still selectable, but they have a grey background instead of blue. This css rule fixes that:

listbox[disabled=true] > listrows {background-color:-moz-dialog; color:-moz-dialogtext; -moz-user-focus: ignore;}
February 28, 2005, 6:21 am pir at cerdecam dot be
This version of the videListBox function is faster than the previously posted. It starts the delete at the last item in the list to avoid reordering of indexes of the list on each deleted item.

I tested both method on a listbox containing 1500 items, this one take around 2 seconds, the other one takes around 8-10 seconds.

function removeAllItems( myListBox )
{

var box = document.getElementById( myListBox );
var rowCount = box.getRowCount();

for( var i = rowCount; i > 0; i-- )
{
box.removeItemAt(i);
}

}

The following method works but should be avoid in the case where you have a lot of items. Not fast enough, it takes around 15 seconds with the same 1500 items as above.

while (list.getRowCount()>1) list.removeItemAt(list.getIndexOfItem(0)) // to avoid
February 24, 2005, 2:16 am nicolas dot n at skynet dot be
No matter the length of the listbox, if you want to remove all the elements, try this:

function videListBox() {
var box = document.getElementById("selected-customers-commands");
var nombreElements = box.getRowCount();
for (var i = 0; i <= nombreElements; i++) {
var item = box.removeItemAt(0);
}
}
January 29, 2005, 7:23 am jussi dot kukkonen at welho dot com
Note to everyone else struggling with listbox.removeItemAt():

There was a bug in the implementation of the function. It was fixed months ago, but apparently the fix didn't make it to Firefox 1.0.

The fix is a two-liner, so patching this by hand isn't hard.
January 3, 2005, 5:26 am nbjayme at yahoo dot com
removeItemAt is not zero-based index. After testing in Win9x/Firefox v1.0
it made a weird result when using removeItemAt(0).

Below is a sample code that'll work with or without headers.


function clearEntries(){
// remove all rows except headers
var objListBox = document.getElementById('mylistbox');
var headerCount = objListbox.getElementsByTagName('listheader').length;

if (headerCount!=0){
var baseRow = 2;
}
else{
var baseRow = 1;
}
while (objListBox.getRowCount() > 0) {
objListBox.removeItemAt(baseRow);
}
}
December 9, 2004, 7:24 pm surkov at dc dot baikal dot ru
<listcell> element may have arbitrary elements as children.

<listbox>
<listitem>
<description value="Type a phrase: "/>
<textbox/>
</listitem>
</listbox>
November 13, 2004, 9:35 pm mrspeaker at gmail dot com
The deleting methods above didnt work for my listbox. I had the listbox defined like this:

<listbox id="lstBox">
<listhead>
<listheader label="Col1"/>
<listheader label="Col2"/>
</listhead>
<listcols>
<listcol flex="1"/>
<listcol flex="1"/>
</listcols>
</listbox>

But deleting using the code above "lstBox.removeItemAt(0)" would erase my whole document as it appears it tries to erase the header row, and then goes bannanas. I had to use "lstBox.removeItemAt( lstBox.getRowCount() + 1 )" to get it to play nice...
October 24, 2004, 10:31 pm aztkgeek at gmail dot com
To delete the selected element use this function (in a better version):

function deleteSelectedIndex() {
// The id name of the list object
var list_id = "list";

// A var to hold the list reference
var list_box;

//Get and hold the referece by the id
list_box = document.getElementById(list_id);

// This is the magic, we call the 'removeItemAt' method and by argument
// we get the selected index from the list by the id
list_box.removeItemAt(document.getElementById(list_id).selectedIndex);
}
October 14, 2004, 2:19 am l0wd3r at notmail dot com
to aztkgeek:

this is too obvious, but wouldnt following code be better for reuse?


function deleteSelectedIndex(list_id) {
list_id = list_id?list_id:"list";
var list_box;
list_box= document.getElementById(list_id);
list_box.removeItemAt(document.getElementById(list_id).selectedIndex);
}
September 27, 2004, 2:59 pm aztkgeek at gmail dot com
To delete the selected element use this function:

function deleteSelectedIndex() {
var list_id = "list";
var list_box;
list_box= document.getElementById(list_id);
list_box.removeItemAt(document.getElementById(list_id).selectedIndex);
}
June 26, 2004, 5:04 pm ian_c at thejolly dot demon dot co dot uk
Given the following multicolumn listbox:-


<listbox id="a_list">
<listcols>
<listcol/>
<listcol/>
<listcol/>
</listcols>
<listhead>
<listheader label="Col 1"/>
<listheader label="Col 2"/>
<listheader label="Col 3"/>
</listhead>
</listbox>


You can append items with some Javascript:-


var list=document.getElementById('a_list');
var item;

item=list.appendItem('Col 1 text');
item.appendChild( document.createElement('listcell') ).setAttribute('label', 'Col 2 text');
item.appendChild( document.createElement('listcell') ).setAttribute('label', 'Col 3 text');


To clear the list without removing the headings you can do:-


var list=document.getElementById('a_list');

while (list.getRowCount()>1) list.removeItemAt(list.getIndexOfItem(0))
April 17, 2004, 6:51 pm moz at supportware dot net
To get multiple columns to populate, try this

var child1 = document.createElement('listcell');
child1.setAttribute('label',"some text");
var child2 = document.createElement('listcell');
child2.setAttribute('label',"some other text");
var item = document.createElement('listitem');
item.appendChild(child1);
item.appendChild(child2);
listbox.appendChild(item);


Then for added fun, to add rows at a particular index :


var thePreviousItem = listbox.getItemAtIndex(index);
var child1 = document.createElement('listcell');
child1.setAttribute('label',"a new row, col 1");
var child2 = document.createElement('listcell');
child2.setAttribute('label',"a new row, col 2);
var item = document.createElement('listitem');
item.appendChild(child1);
item.appendChild(child2);
var insertedItem = listbox.insertBefore(item,thePreviousItem);


To then select that row:


listbox.scrollToIndex(index);
listbox.selectItem(insertedItem);
listbox.focus(); // not strictly needed, but when a button is triggering..
February 18, 2004, 8:54 am dc at blendedfellowship dot com
You could use the following function to clear the entire list of the listbox...

XUL Listbox:

<listbox id="MyShoppingList" flex="1">
<listitem label="Apples" />
<listitem label="Peaches" />
</listbox>


Javascript:

function clearListBox() {
lstBox = document.getElementById('MyShoppingList');
while (lstBox.getRowCount() > 0) {
lstBox.removeItemAt(0);
}
}
January 28, 2004, 2:40 am murray dot bryant at harmonygold dot com dot au
Just adding to previous comment
this is how you add items to a listbox with multiple cells


var item = document.createElement('listitem');

var child1 = document.createElement('listcell');
child1.setAttribute('label',name);
item.appendChild(child1);

var child2 = document.createElement('listcell');
child2.setAttribute('label',text);
item.appendChild(child2);

listbox.appendChild(item);
January 18, 2004, 7:03 am hfuecks at phppatterns dot com
Quick example of how you might append listItems to a listbox. If you had XUL defining a listbox like


<listbox id="MyShoppingList" flex="1">
<listhead>
<listheader label="Shopping List"/>
</listhead>
<listcols>
<listcol flex="1"/>
</listcols>
<listitem>
<listcell label="Apples" />
</listitem>
</listbox>


With JavaScript you could append items like;


shoppingList = document.getElementById('MyShoppingList');
shoppingList.appendItem('Milk','');
shoppingList.appendItem('Bread','');
shoppingList.appendItem('Butter','');


The second argument (which I've passed here as an empty value) corresponds to the value attribute of a listbox.

Have yet to work out how to append items to a listbox with more than one column...

Copyright © 1999 - 2005 XULPlanet.com