Someone can tell me why this code does everything but work under IE
(6)???
var newEditor = new Option(document.add_editor.nome.value,
document.add_editor.nome.value);
opener.document.newsform.editor.options.add(newEditor, null);
opener.document.newsform.editor.selectedIndex =
opener.document.newsform.editor.length - 1;
The problem here is that Microsoft, for some reason, implemented the DOM
method, HTMLSelectElement.add(), but changed its signature. Instead of the
second argument being a required object reference (or null), it's an
optional ordinal number.
Unfortunately, this means having to cope with two completely incompatible
methods. There are three ways to deal with this problem, but I wouldn't
call any of them attractive:
1) Detect IE and call the relevant method.
2) Use try/catch, trying one set of parameters then the other.
3) Use the older "new Option" approach for all cases.
The first two options are unreliable. A lot of browsers disguise
themselves as IE, so detecting IE with any certainty is impossible. The
use of try/catch depends upon it existing in the first place; they are
fairly recent commands, and there's no real way to check if they can be
used, but this would be the best, otherwise.
The third option, whilst useable, shouldn't (in my opinion) be used for
anything other than a fallback approach for old browsers that don't
support the DOM.
Secondly, whilst this isn't a problem, I wouldn't advise it: mixing two
approaches.
When you use the older "new Option" approach, you add the resulting
element using the HTMLSelectElement.options collection, simply assigning
where you want the option to go.
When you use the newer DOM approach with document.createElement(), you add
the resulting element using HTMLSelectElement.add().
So choose either:
var newEditor = new Option(
document.add_editor.nome.value,
document.add_editor.nome.value);
opener.document.newsform.editor.options[
opener.document.newsform.editor.length] = newEditor;
or:
var sel = opener.document.newsform.editor;
if(document.createElement && sel.add) {
var newEditor = document.createElement('OPTION');
if(newEditor) {
var e;
newEditor.text = newEditor.value =
document.add_editor.nome.value;
try {
sel.add(newEditor, null);
} catch(e) {
sel.add(newEditor);
}
}
}
By the way, you should look into saving object references, rather than
accessing each element using its fully qualified reference. It's more
efficient and makes for a smaller script. For example:
var f = document.forms['formName'];
var e = f.elements['controlName'];
or
var c = document.forms['formName'].elements;
var e = c['controlName'];
Which you choose depends upon whether you need to access properties of the
form, or just its controls.
Mike