views:

30

answers:

3

Hi, im trying to delete a HTML select list. This is what im using:

var size = DID(SourceDiv + Number).options.length;
    DeleteSelectElements(SourceDiv+Number,size);

function DeleteSelectElements(Div,Len){
    var k;
    var Length = Len
    for (k = 0; k < Length; k++) {
        DID(Div).options[k] = null;
    }
}

DID just returns the actual HTML element. The problem is that only EXACTLY hald the list is being deleted. The Len parameter is changing because it relates to size, which related to the actual length of the list. So when i delete in the function its actually changing 'Length' and never reaching the actual end of the list :s

A: 

You can only delete the first element! When you delete it, second one becomes the new first... so delete Length of first elements?

function DeleteSelectElements(Div,Len){
    var k;
    var Length = Len
    for (k = 0; k < Length; k++) {
        DID(Div).options[0] = null;
    }
}
Cipi
+1  A: 

You already discovered the problem: every time you delete an element, the length decreases, which means the number of valid indices also decreases by one. So, instead of trying to delete from 0 to Length, just continually delete the first element until the list is empty:

var e = DID(Div).options;
while (e.length > 0)
  e.remove(0);
casablanca
+1! Elegant solution!
elusive
+1  A: 

of course it is: if you have a list of 10 things and you do delete the first 5, your iterator (k) is 5, your length is 5 so ((k < Length) == false) and it stops just keep deleting the first element instead of the 'current' element. or just loop it backwards :) for optimizations:

var blah = DID(Div).options;
for(k = Length; k > 0; k--)
{
    blah[k - 1] = null;
}
DoXicK