Clearing a select box
13th December 2002
Deep in to coursework now, but I just spent more time than I care to mention struggling with what should have been a very simple task; removing all of the items from an HTML select box using Javascript. Here’s the code that was causing me problems:
endSelect = document.getElementById('endSelect'); /* Clear out the current options */ for (i = 0; i < endSelect.options.length; i++) { endSelect.options[i] = null; }
For some reason, this was only removing approximately half of the items in the list. I checked it in both IE and Phoenix and the same bug was evident, demonstrating that it was almost certainly a flaw in my code rather than a strange browser bug. After much tweaking and adding of alert()
debugging statements I realised my folly: Every time the loop went round I was removing an item from the list of items in the select box, but my code was not taking this in to account (a classic example of changing a data stucture while processing it). Once this had dawned on me the replacement code took a matter of moments:
while (endSelect.options.length > 0) { endSelect.options[0] = null; }
Hopefully this will soon be Googled and will eventually save someone else from making the same stupid mistake.
More recent articles
- Gemini 2.0 Flash: An outstanding multi-modal LLM with a sci-fi streaming mode - 11th December 2024
- ChatGPT Canvas can make API requests now, but it's complicated - 10th December 2024
- I can now run a GPT-4 class model on my laptop - 9th December 2024