Jump to content

Can't remove all options from a selection field


boylesg
 Share

Recommended Posts

function emptyOptions(lpszSelFieldID){	var SelField = document.getElementById(lpszSelFieldID);	var strTxt = "";		for ($I = 0; $I < SelField.length; $I++)	{		strTxt = $I;		strTxt += " ";		strTxt += SelField.length;		alert(strTxt);		SelField.remove($I);	}}

Using alert reveals that SelField.length is the correct value in all circumstances.

But regardless of this the loop only iterates once when SelField.length greater than 1.

If I comment out SelField.remove($I) then the loop iterates the correct number of times.

 

So I don't get it. Why does the call to SelField.remove($I) fail (and cause the loop to break prematurely) for $I > 0 when SelField.length is greater than 1?????

 

Does remove still work if you have not numbered the options? As in <option value="0"> etc

 

 

Link to comment
Share on other sites

when the length is zero, the while loop never runs in the first place but when $I is actually less than the length of SelField the while loop runs (which is why its not breaking when the length is 0). the reason why SelField.remove($I) is breaking (and is VERY likely throwing an error, check the console) is because $I is an invalid parameter. remove() expects an actual element that SelField contains, in this case an option or optgroup element, and $I is NOT an element but a simple number.

 

also I'm sure remove() is not the function you want. remove() will destroy the option, making it no longer exist and you unable to reselect or view it. You'll want to change SelField.selectedIndex, as that is what's used to point to a specific option.

 

one more thing, while $I is actually a valid identifier, you should avoid writing it as such. At 1st, I thought you were writing PHP. And don't forget to include a var keyword. it'd be bad if you somehow had some other $I in some outer scope now or in the future and this small loop messed it all up. the var keyword will imply that this $I is unique only to this scope and does not affect any other $I that is possibly written in an encompassing scope.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...