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
- Qwen2.5-Coder-32B is an LLM that can code well that runs on my Mac - 12th November 2024
- Visualizing local election results with Datasette, Observable and MapLibre GL - 9th November 2024
- Project: VERDAD - tracking misinformation in radio broadcasts using Gemini 1.5 - 7th November 2024