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:


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.

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>
<window id="treeSelect" title="Tree Selection"
function doSelect(event)
  // the tree is the target of the event
  // 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 value="Selected Part:"/>
  <label id="selectedLabel" value=""/>
<tree flex="1" width="350" height="200" onselect="doSelect(event);">
    <treecol id="part" label="Part Number" primary="true" flex="1"/>
    <treecol id="description" label="Description" flex="1"/>
        <treecell label="I68-023"/>
        <treecell label="Flux Capacitor"/>
        <treecell label="P34-912"/>
        <treecell label="Continuum Transfunctioner"/>
        <treecell label="Z29-307"/>
        <treecell label="Deluxe Transmogrifier"/>
Copyright © 1999 - 2005