开发者

Load two dropdowns with the same values

开发者 https://www.devze.com 2023-01-19 20:54 出处:网络
Is there any problem with loading the same set of values in 2 different HTML form dropdowns? My code looks like this:

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.


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: What is the most efficient way to deep clone an object in JavaScript? .

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


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);


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/

0

精彩评论

暂无评论...
验证码 换一张
取 消