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
- Weeknotes: Llama 3, AI for Data Journalism, llm-evals and datasette-secrets - 23rd April 2024
- Options for accessing Llama 3 from the terminal using LLM - 22nd April 2024
- AI for Data Journalism: demonstrating what we can do with this stuff right now - 17th April 2024
- Three major LLM releases in 24 hours (plus weeknotes) - 10th April 2024
- Building files-to-prompt entirely using Claude 3 Opus - 8th April 2024
- Running OCR against PDFs and images directly in your browser - 30th March 2024
- 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