Simon Willison’s Weblog


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.

This is Clearing a select box by Simon Willison, posted on 13th December 2002.

Next: Creative commons launch

Previous: Joe Clark interviews

Previously hosted at