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
This is working great for me in IE, but fails to deselect the list in FireFox or Safari. Any ideas?
# Posted By Denny | 6/3/08 5:10 PM
@Denny,

You're using the second shorter snippet? This one worked for me in Firefox.
# Posted By Jacob Munson | 6/3/08 5:13 PM
document.getElementById("templateList").value = ""
this work for me
# Posted By ivan | 6/12/09 2:22 AM
Saved me a lot of troubleshooting! Thanks!!
# Posted By Siobhan | 4/28/10 11:22 AM
hi jake,

i m facing some problems inside transfer options in my code,so i gone through with your code and i apply it to my code as well but my code is not going inside the for loop of your code.its not taking the value of templateList.options.lengtgh,can you help me how to reach inside the for loop of your code....

var templateList = document.getElementById('templateList');

for (var i = 0; i < templateList.options.length; i++)//inside this my code is not reachable
{
templateList.options[i].selected = false;
alert(templateList.options[i].selected)
}
# Posted By Deepak sharma | 6/15/11 8:52 PM
Deepak,

That for loop didn't work (it was the code that I was trying that would NOT work. This is the code I found that works:
document.getElementById("templateList").selectedIndex = -1
# Posted By Jake Munson | 6/16/11 10:46 AM
BlogCFC was created by Raymond Camden. This blog is running version 5.9. Contact Blog Owner