faqts : Computers : Programming : Languages : JavaScript : Forms : SELECT

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

456 of 505 people (90%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I add OPTIONs to a SELECT list?
How can I delete OPTIONs from a SELECT list?
I did not understand How to delete item from select online

May 12th, 2008 20:36
i can do it, diana b, Sam Thomas, Martin Honnen, Nathan Wallace, dharma gummi,


You create a new OPTION with
  var opt = new Option('text', 'value');
and insert it with
  var sel = document.formName.selectName;
  sel.options[sel.options.length] = opt;
at the end of the SELECT list. To insert into the middle move other 
options up e.g.
  function insertOptionAt (select, option, index) {
    for (var i = select.options.length; i > index; i--)
      select.options[i] = select.options[i - 1];
    select.options[index] = option;
  }
  // example call 
  insertOptionAt (document.formName.selectName, 
                  new Option('text', 'value'), 3);
You delete an OPTION simply be setting
http://www.stupidarticles.com
http://www.halazona.com
http://www.shikapika.com
http://www.stakoza.com
http://www.uploadarticles.com
http://www.ganazat.com
http://www.damima.com
http://www.tarabiza.com
http://www.articlesxarticles.com
http://www.articlesfreedirectory.com
  var sel = document.formName.selectName;
  sel.options[optionIndex] = null;
Note that NN2/3/4 on windows and mac will insert/delete the option that 
way but not update the screen display of the SELECT unless you call
  history.go(0)
So do all your changes to a SELECT and then call
  if (navigator.appName == 'Netscape' && 
      (navigator.appVersion.indexOf('Win') != -1 ||
       navigator.appVersion.indexOf('Mac') != -1))
    history.go(0);
to get the display updated if necessary. Be aware that calling 
history.go(0) reloads the document so make sure your code adding or 
deleting options is NOT called in BODY ONLOAD as then you get an 
infinite loop.
Alternately, you can resize the window by a pixel and resize it back, 
which has the same effect without forcing a complete reload of the page.
Example:
   window.resizeBy(1,1);
   window.resizeBy(-1,-1);
IE4/5 and NN6 have other ways of inserting and deleting OPTIONs 
into/from a SELECT but the above code is cross browser and therefore 
recommended unless you are sure you target only a particular browser.