SiteExperts.com Logo Home | Community | Developer's Paradise | Jobs
User Groups | Site Tools | Site Information | Search

Inside Technique : Databound Listboxes
By Scott Isaacs

Databinding allows you to associate external data with your page. One common use of data binding is to populate an HTML <SELECT> element. Currently the HTML data binding only supports binding to the selected value of a list box. There is no built-in mechanism for populating the listbox. Instead, you must write a script that manually fills the list box. This script builds on the technique introduced in Programming Databound Lists.

Both of the lists below are being populated from an external text file named links.txt. If you looked closely when the page loaded, the initial value of the listbox was Loading..., and the listboxes were initially disabled. Once the data is downloaded, a script populates and reenables the listboxes with the actual data:

With Internet Explorer 4.0, you would see select controls with the bound data.

The above approach is very useful when the list of data changes often. Rather than modify the actual HTML page, you only need to modify the database or text file that contains the data.

Code

 <SCRIPT LANGUAGE="JavaScript">
 function populateList(target, src, order) {
  // target - The list box to populate
  // src - The datasource object
  // order (boolean) - true - the order of the recordset
  //                   false - the reverse order of the recordset
  var rc = src.recordset
  rc.moveFirst()
  var el
  target.remove(0)
  while (!rc.eof) {
    // Create new option element
    el = new Option
    // Display first column
    el.text = rc.Fields(0).value  
    // Set value to second column
    el.value = rc.Fields(1).value
    // Add to list box
    if (order) 
      target.add(el)
    else
      target.add(el,0)
    rc.moveNext()
  }
  // reenable the list box
  target.disabled = false
 }
</SCRIPT>

<SCRIPT language=javascript for=links event=ondatasetcomplete()>
 // When the data is loaded, populate the listboxes
 populateList(document.all.list, document.all.links, true)
 populateList(document.all.list2, document.all.links, false)
</SCRIPT>

Internet Explorer 4.0 also supports extensions to HTML for automatically binding to tables. We use this approach to demonstrate creating a list of favorite links and use this feature in many areas of the web-site.

Discuss and Rate this Article