views:

36

answers:

3

Hi all:

Is there any problem with loading the same set of values in 2 different HTML form dropdowns? My code looks like this:

var dr1=document.getElementById("dr1");
var dr2=document.getElementById("dr2");
for (nombre in elements) {
    var opcion=document.createElement('OPTION');
    var cam=elements[nombre];
    opcion.value=nombre;
    opcion.text=cam["nombreCompleto"];
    //Añadimos a los 2 dropdowns
    dr2.add(opcion, null);
    dr1.add(opcion, null);
    }
dr1.selectedIndex=0;
dr2.selectedIndex=0;

This load the same set of values to two different dropdowns. However, when executed, it only loads whatever dropdown appears last in the code; in the above example, it would have been "dr1" (and if I put the "dr2.add(option.null)" line last, it loads that one). If I load only one dropdown (commenting out the other one) it works fine.

All of this is on Firefox 3.6.10.

A: 

Yes, your OPTION objects will first be added to dr2, then to dr1. There won't be created copies when calling add, but the object you just created will be moved from nowhere to dr2, then to dr1.

The general idea is that you can't have a DOM object in two different places at the same time. You may want to take a look into JavaScript object cloning. See here for some useful information: http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-a-javascript-object .

If you just need to clone DOM element objects you can use cloneNode(). See here for a complete list of available members and methods: http://www.w3schools.com/jsref/dom_obj_all.asp

Alin Purcaru
A: 

No, it doesn't work. Refactor the code to create the option node into a function.

function createOption(...) {
    var opcion=document.createElement('OPTION');
    var cam=elements[nombre];
    opcion.value=nombre;
    opcion.text=cam["nombreCompleto"];
    return opcion;
}

dr1.add(createOption(), null);
dr2.add(createOption(), null);
A: 

To add it to the second element just clone it ..

dr2.add(opcion, null);
dr1.add(opcion.cloneNode(true), null);

example at http://www.jsfiddle.net/7Kxdu/

Gaby