HTML/JavaScript - Add options from a new window

Add options to a select box from a new window

Tutorial008 - Try It

After clicking Open below, select an option in the new window and click Add.

Fail technique

If you try to add a new option by directly referencing a select element from a new window via window.opener, you may get the following error:
The server threw an exception.

You can test this failure in example above. After clicking Open above, click fail technique in the new window. When I tested it in Internet Explorer 6.0, I got the aforementioned error message. In Opera 8.02, nothing happened and no error showed up in the JavaScript console. In Firefox 1.0.6, it added the option without error.

To avoid the error entirely, I would recommend calling a method that's in the main window, and passing in the text and value you want. This is what's done in the example above when clicking Add in the new window. I tested that code in the same browsers and it worked in each one.

Source

Main page JavaScript

// mredkj.com
// 2005-09-20
// version: beta
function openInNewWindow()
{
  var aWindow = window.open('tutorial008_nw.html', 'Tutorial008',
   'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=430');
}
function addOption(theText, theValue)
{
  var theSel = document.getElementById('selOriginalWindow');
  var newOpt = new Option(theText, theValue);
  var selLength = theSel.length;
  theSel.options[selLength] = newOpt;
}

New window JavaScript

// mredkj.com
// 2005-09-20
// version: beta
function addOptions()
{
  var newSel = document.getElementById('selNewStuff');
  if (newSel.selectedIndex != -1) {
    var newText = newSel.options[newSel.selectedIndex].text;
    var newValue = newSel.options[newSel.selectedIndex].value;
    window.opener.addOption(newText, newValue);
  }
}

Fail technique

// The following function may not work,
// possibly with the error "The server threw an exception."
function failTechnique()
{
  var optX = new Option('yourText', 'yourValue');
  var selX = window.opener.document.getElementById('selOriginalWindow');
  selX.options[selX.length] = optX;
}
About this page: