View Full Version : creating option field with appendChild

02-12-2004, 04:22 PM
Hey guys, I'm creating a new field using the document.createElement, this is a new option for a select but cannot make the text to appears, I tried everything "but the correct syntax" i'm sure, can you help????

var parent = document.getElementById("box4");
var children = parent.all.tags("select");
var son = children[0];
var option = son.children.op1;
option.text = "text modified";

var txtFld = document.createElement("option");
//txtFld.setAttribute("type","new option");
txtFld.setAttribute("text","the new option text");
txtFld.setAttribute("id", "id2");

02-12-2004, 06:05 PM
I've got a Select class which encapsulates this functionality into a method, and works in Gecko browsers and IE6:

function Select (elName) {
this.element = document.createElement('select');
this.element.id = this.element.name = elName;

Select.prototype.populate = function (text, values) {
if (!text || typeof(text) == 'string') {
if (typeof(values) == 'undefined' || typeof(values) == 'string') {
values = text;
var end = Math.max(text.length, values.length),
i = 0, o;
do {
this.addOption(text[i], values[i]);
} while (end > ++i);

Select.prototype.addOption = function (text, value, before) {
var o = document.createElement('option');
o.text = text;
o.value = value;
if (!before) {
before = null;
try {
this.element.add(o, before)
} catch (er) {
try {
if (!isNaN(before) && before != null) {
before = this.element.options[before];
this.element.add(o, before);
} catch (err) {

You can see that it doesn't use the appendChild() method, mainly because I couldn't get it to work either, no matter how hard I tried. Then comes the fact that IE and Gecko implement different versions of the same add() method, where in some cases the second argument is required to be a number, and in others it's required to be a node, and in some cases it's optional, others required.

At least it's not as bad a PITA as radio buttons.

02-12-2004, 06:57 PM
The way you would do it is as follows:

children[0].options[0] = new Option("Text", "Value");
children[0].options[1] = new Option("Text", "Value");
children[0].options[2] = new Option("Text", "Value");
children[0].options[3] = new Option("Text", "Value");

The options array has no bounds on it -- at least I've never tested the bounds...

Hope that helps,

02-12-2004, 07:12 PM
Great !!! that's the solution I was looking for, and just came to my mind. you can even do...

children[0].options[children.length++] = new Option("Text", "Value");
so you don't have to worry about the correct index..."in case you want the new element at the end"...

Thanks again Friends....