View Full Version : IE7 & 8 won't set selected on select-options

09-16-2010, 11:34 AM

I have a problem as seen in the title, it works fine in Firefox 3.6.9 and Chrome 6.0. This is the code not working, throws no errors though:

var options = document.getElementById( 'mainForm:content:userTemplateSelect' ).getElementsByTagName( 'option' );
for( i = 0; i < options.length; i++)
options[i].selected = false;

I use this to clear the selected item from a html select (t:selectOneListbox in JSF)
Any help would be appreciated:)

09-16-2010, 01:06 PM
What are you really wanting to do? Technically speaking, without javascript a select must have at least one option selected. Or, if not technically, then logically - If you have a select with no options, it's invalid. If a select with options has none of them with the selected attribute hard coded, then when that select loads for the first time, the first option is selected.

Let's get back to my question, what do you want to do? You're code is attempting to wipe out the select, give it no value, none selected, all false. Would reseting (what your code does in Firefox anyway) it to its original value be OK? For a typical select, that would be the first option, 0. If you really want to wipe out its value, you can set the option to -1.

Try this:

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function clearSelects(){
var selects = document.getElementById('mainForm:content:userTemplateSelect').getElementsByTagName('select');
for(var i = 0; i < selects.length; ++i){
selects[i].options.selectedIndex = 0;
<form action="#" id="mainForm:content:userTemplateSelect">
<select name="whatever">
<option value="">Please Select</option>
<option value="louie">Louie</option>
<option value="bob">Bob</option>
<option value="edna">Edna</option>
<option value="sally">Sally</option>
<option value="sid">Sid</option>
<input type="button" value="Clear Options" onclick="clearSelects();"><br>
<input type="submit" value="Go">

See that red 0? If you really want to wipe out the value, change it to -1.

09-16-2010, 01:29 PM

That actually worked:)

I should have mentioned that my select has a size > 1, thereby a select list, not a drop down. All browsers including IE was able to show it with no elements selected from the beginning.

Thanks again:)

09-16-2010, 01:31 PM
What I was trying to do by the way, was to have two select lists that were mutually exclusive..