WARNING: Most of this content (with the exception of the Mozilla 1.9 XPCOM reference) is very old, and can be expected to be out of date and possibly obsolete. For better XUL documentation, please visit the XUL hub at the Mozilla Developer Center.
How do I get the text of the currently selected item in a tree?
You can get the text of the current selected cell in a tree using the following code:
tree.view.getCellText(tree.currentIndex,column)
The tree's currentIndex property holds the index of the selected row in the tree. Pass this row, along with the id of the column, to the function getCellValue. Not that the row is a number whereas the column is an id, specifically, the id of a treecol element.
Use the onselect attribute on the tree element to have script execute when a row is selected. The following example demonstrates this. Selecting a row will display the corresponding cell's text in a label above.
View
<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="treeSelect" title="Tree Selection"
xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul">
<script>
function doSelect(event)
{
// the tree is the target of the event
var tree=event.target;
// get the label element
var label=document.getElementById("selectedLabel");
// get the text of the description column in the selected row.
// First, call the getCellText function of the tree's view.
// We need to supply two parameters, the selected row index
// held in the tree's currentIndex property and the id of the
// column.
var txt=tree.view.getCellText(tree.currentIndex,"description")
// assign the text to the label.
label.setAttribute("value",txt);
}
</script>
<hbox>
<label value="Selected Part:"/>
<label id="selectedLabel" value=""/>
</hbox>
<tree flex="1" width="350" height="200" onselect="doSelect(event);">
<treecols>
<treecol id="part" label="Part Number" primary="true" flex="1"/>
<treecol id="description" label="Description" flex="1"/>
</treecols>
<treechildren>
<treeitem>
<treerow>
<treecell label="I68-023"/>
<treecell label="Flux Capacitor"/>
</treerow>
</treeitem>
<treeitem>
<treerow>
<treecell label="P34-912"/>
<treecell label="Continuum Transfunctioner"/>
</treerow>
</treeitem>
<treeitem>
<treerow>
<treecell label="Z29-307"/>
<treecell label="Deluxe Transmogrifier"/>
</treerow>
</treeitem>
</treechildren>
</tree>
</window>
