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
- llm cmd undo last git commit - a new plugin for LLM - 26th March 2024
- Building and testing C extensions for SQLite with ChatGPT Code Interpreter - 23rd March 2024
- Claude and ChatGPT for ad-hoc sidequests - 22nd March 2024
- Weeknotes: the aftermath of NICAR - 16th March 2024
- The GPT-4 barrier has finally been broken - 8th March 2024
- Prompt injection and jailbreaking are not the same thing - 5th March 2024
- Interesting ideas in Observable Framework - 3rd March 2024
- Weeknotes: Getting ready for NICAR - 27th February 2024
- The killer app of Gemini Pro 1.5 is video - 21st February 2024
- Weeknotes: a Datasette release, an LLM release and a bunch of new plugins - 9th February 2024