html – Javascript loop limit to delete select list keeps changing – Education Career Blog

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).optionsk = 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

,

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

,

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--)
{
    blahk - 1 = null;
}

,

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).options0 = null;
    }
}

Leave a Comment