----- Original Message -----
From: "SAM" <
[email protected]>
Newsgroups: comp.lang.javascript
Sent: Thursday, October 29, 2009 5:26 PM
Subject: Re: repopulating my select
Le 10/29/09 9:01 PM, Davey a écrit :
to change the options in my select element
i set options.length to zero then use
y = document.createElement('option');
and add(y,null) in a loop
I'm wondering what happens to all
=============== exercise 1: select reduced to one option
var f = document.forms[0];
f = f.elements['mySelect'];
f.length = 0; // empty select
var o = new Option('aText', 'aValue');
f[f.length] = o;
alternative==============select reduced to one option
var f = document.forms[0];
f = f.elements['mySelect'];
f.length = 1; // set length to one
f[0].text="aText";
f[0].value="aValue";
================ exercise 2: empty and refill a select
var s = []; // s is an array (empty)
var f = document.forms[0].mySelect, n = f.length;
// filling the array with the select's options
while(n--) s[n] = [f.options[n].text, f.options[n].value];
// empty the select
f.length = 0;
// re-fill the select
n = s.length;
while(n--) f[n] = new Option(s[n][0], s[n][1]);
alternative============== empty and refill a select
var s = []; // s is an array (empty)
var f = document.forms[0].mySelect, n = f.length;
// filling the array with the select's options
while(n--) s[n] = [f[n].text, f[n].value];
// empty the select
f.length = 0;
// re-fill the select
n = s.length;
f.length=n;
while(n--){
f[n].text = s[n][0];
f[n].value = s[n][1];
}
================= exercise 3: copy a select
var S1 = document.forms[0].select1,
n = S1.length;
var S2 = document.createElement('SELECT');
S2.name = 'select2';
while(n--) S2[n] = new Option(S1[n].text, S1[n].value);
document.forms[0].appendChild(S2);
alternative==============copy a selectvar
var S1 = document.forms[0].mySelect,
n = S1.length;
var S2 = document.createElement('SELECT');
S2.name = 'mySelect2';
S2.length = n;
while(n--){
S2[n].text = S1[n].text;
S2[n].value = S1[n].value;
}
document.forms[0].appendChild(S2);
Are these alternatives "bad", what about Gargage Collection ?
They work in all browsers I test with
(ie, firefox and opera on windows and firefox on linux ).