PDA

View Full Version : for loops


IKinsler
07-23-2003, 01:08 AM
function gotostage2 (next) {
for (s=1;s<=document.remove.stage2.options.length;s++) {
document.remove.stage2.options[s] = null;
}
}

function gotostage3 (next) {
for (l=1;l<=g[next].length;l++) {
document.remove.stage2.options[l] = new Option (g[next][l - 1], '');
}
}

when i call gotostage3() it does what it should and adds the array g[next] to the select box.. HOWEVER when i call gotostage2() it only removes some of the entires in the select box. i can call the finction a few times, and each time it removes a few more until they are all gone

any ideas :S

- jared

fredmv
07-23-2003, 01:36 AM
Heh, there's actually a little trick I know of that, if you set the length property of the select element to 0, it will get rid of all options contained in it. So for the gotostage2 function, try this:


document.remove.stage2.length = 0;


That should work perfectly, no loops required.:thumbsup:

Good luck.

glenngv
07-23-2003, 03:51 AM
fredmv is correct.
but let me explain what happens inside the loop.

in the first loop (s=1), it removes the 2nd option (yes 2nd, not 1st bec. option index start at 0!). all the options below it will go up. the 3rd option becomes 2nd, 4th to 3rd, and so on...
in the 2nd loop (s=2), it removes the 3rd option, which leaves the new 2nd option undeleted! this goes on until the end of the loop.
moreover, the number of loops decreases because the condition is s<=document.remove.stage2.options.length.
this is because if you remove the option, the length decreases.

so aside from setting the length of the option to zero to remove all the items, the function could be like this:

function gotostage2() {
var len = document.remove.stage2.options.length;
for (s=0;s<len;s++) {
document.remove.stage2.options[0] = null; //always remove the first item
}
}

take note that option items start at 0 not 1 as you originally set.

but of course, document.remove.stage2.options.length = 0 is the better solution. :D

IKinsler
07-24-2003, 01:56 AM
thanks very much... actually i dont want the first entry deleted, only 1 and on..

and also i will use the length=0 and then reset the first item..

and lastly, i realized that just after i submitted this, and i changed my code from .options[o] (or whatever var it was) to .options[1] so it would always remove variable 1..


jared

glenngv
07-24-2003, 03:54 AM
so the code could also be like this:

function gotostage2() {
var len = document.remove.stage2.options.length;
for (s=1;s<len;s++) {
document.remove.stage2.options[1] = null; //always remove the 2nd item
}
}