Deselect all items in a Select List

Say you want to have a "unselect all" button for a select list, how would the JavaScript work? I just spent too long trying to figure out how to do this in IE. As usual, I got it to work in Firefox right away, but IE doesn't work the same way.

Here's the code that worked in Firefox, but not in IE:

var templateList = document.getElementById('templateList')
for (var i = 0; i < templateList.options.length; i++) {
templateList.options[i].selected = false
alert(templateList.options[i].selected)
}

I tried all kinds of variations of the above, and nothing worked in either IE 6 nor 7. I finally found this, which I like better anyway:

document.getElementById("templateList").selectedIndex = -1

And that works in both Firefox and IE. I can't wait for all the browsers to pass the Acid 3 test...

Comments
Succinct!
# Posted By Timbo | 3/19/08 9:23 AM
cool I like it. I'll probably use it for the next time I do a select. I assume it works the other way too, as in
document.getElementById("templateList").selectedIndex = 1;

regards,
larry
# Posted By Larry C. Lyons | 5/9/08 11:50 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner