Welcome to MSDN Blogs Sign in | Join | Help

Using JScript in DHTML to Manipulate Objects in a SELECT tag

The following code can be used to dynamically add, remove or select all items in a SELECT object.  The code assumes that when objects are added to the SELECT object, that the display text and value are identical. 

<script language="javascript"> 
   function addToList(txtBox, selectBox){ 
      var oOption = document.createElement("OPTION"); 
      oOption.text = txtBox.value; 
      oOption.value = txtBox.value; 
      selectBox.add(oOption); 
      txtBox.value = ""; 
      txtBox.focus(); 
   } 

   function removeFromList(selectBox){ 
      selectBox.remove(selectBox.selectedIndex); 
   } 

   function selectEntireList(selectBox){ 
      var fromObj = selectBox; 
      for ( selIndex = fromObj.length; selIndex -- ; selIndex > 0 ){ 
         if(fromObj.options[selIndex].text != ""){ 
            fromObj.options[selIndex].selected = true; 
         } 
      } 
   }
</script>

Published Saturday, March 05, 2005 12:23 PM by anthonw
Filed under:

Comments

# re: Using JScript in DHTML to Manipulate Objects in a SELECT tag

After spending 10 minutes on analysing the for loop in selectEntireList I have to admit it is pure zen: iterating throught the options bottom-to-top without a var si = sel.options.length - 1 as initial index by swapping the for's increment (decrement here) and test are just masterly done. Placing the selIndex > 0 test in the increments place for documentional reasons is ingenious :D

I really like this loop.

-- b.gr

PS: to add something more serious to this comment: a few tests on dynamically adding options to selects can be found at http://xkr.us/js/dynsel
Saturday, March 05, 2005 4:49 PM by Bjoern Graf
New Comments to this post are disabled
 
Page view tracker