DelphiFAQ Home Search:
General :: Programming :: JavaScript
Code snippets to add functionality to your HTML pages, preferably cross-browser.


This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

RESET button in my form does not restore my listbox content


My form uses javascript to populate a SELECT listbox with zip codes chosen by the user. The zip code listbox could have any amount of entries. When the user presses the form's RESET button, it does not restore the listbox to its original entries.


The reason that a reset button will not restore a SELECT listbox is because such a SELECT list is considered to be static. The user would normally only change which item(s) is(are) selected. Your form's reset button will indeed try to restore the original selection.

What you need to do is have a second copy of that listbox on your form, but hidden. This copy will never be used. To hide a listbox you need to assign the style visibility="hidden".

Then put an onclick() event on that listbox. In the onclick event call the function copy_listbox which is shown below. It takes two arguments where tgt is the target listbox (the one that will be filled) and src is the source listbox - the one that will be duplicated.

In your case you would call
copy_listbox(zipcode_list, hidden_list)

Ideally your server side script which generates the original HTML form will provide the hidden copy and make sure it has the same content. If that is not possible, you can include an empty hidden listbox and in the body onload() event, call copy_listbox with inverted parameters.

function copy_listbox(tgt,src) {
   var lb=document.getElementById(tgt);
   // clear the input listbox
  for (var i=lb.options.length-1; i>=0; i--){
     lb.options[i] = null;
   lb.selectedIndex = -1;
   // restore it

   var bk=document.getElementById(src);
   for (var i=bk.options.length-1; i>=0; i--){
     oOption = document.createElement("OPTION");
     // Append to end of list
    oOption.text = bk.options[i].text;
     oOption.value = bk.options[i].value;
     oOption.selected = false;
     lb.options[lb.options.length] = oOption;

Generated 4:01:30 on Aug 3, 2020