Re: Replace all values in a Listbox
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.javascript archive

Re: Replace all values in a Listbox

From: Thomas 'PointedEars' Lahn <PointedEars@web.de>
Date: Sat Apr 29 2006 - 01:39:08 CEST

IanONet@gmail.com wrote:

> I have used
> onChange="ReplaceValues(this.options[this.selectedIndex].value)" to
> change several textbox values when a user makes a selection from a
> Select List.

Only that there is no such built-in method. Which is why this information
is of little value to other people.
 
> Now I have the requirement to replace all the values in another Select
> List when a selection is made on the first Select List.

You are about the 4711th person to ask this here. Search the archives.
 
> There are two questions: What is the Javascript syntax for deleting and
> replacing option values in a Select List

- Deleting an option:

    delete selectRef.options[index];

  If that does not work:
  
    selectRef.options[index] = null;

- Shortcut for deleting all options: selectRef.options.length = 0;
  Fall back to a loop of the previous if that does not work.

- Replace option value:

    selectRef.options[index].value = "...";

- Add new option:

    selectRef.options[selectRef.options.length] = new Option(...);

> and how would you (how should I ) store the data that
> I will be using to repopulate an existing Select List.

This has been asked before, too. One possibility is:

  var data = {
    sel1Value1: [
      {text: ..., value: ...},
      ...
    ],

    sel1Value2: [
      ...
    ],
   
    ...
  };

and then:

  <script type="text/javascript">
    function repopulate(oSrc, sTgt)
    {
      var oTgt = oSrc.form.elements[sTgt];
      if (oTgt)
      {
        // TODO: delete all options of oTgt;
        // maybe it is more efficient to overwrite existing options
        // and delete only those that are no longer needed

        var
          curVal = oSrc.options[oSrc.selectedIndex],
          curData = data[curVal];
        
        for (var i = 0, len = curData.length; i < len; i++)
        {
          // TODO: add new option using properties of curData[i]
        }
      }
    }
  
  <select ... onchange="repopulate(this, 'sel2');">

The data is best generated server-side, by a server-side fallback to handle
the case that client-side script or DOM support is not available.

PointedEars

-- 
There are two possibilities: Either we are alone in the
universe or we are not. Both are equally terrifying.
  -- Arthur C. Clarke
Received on Mon May 1 05:26:22 2006