Can an HTML <select> element have a default selectedIndex of -1 without running page-wide javascript?
Solution 1
You may use the following: By default the first option will be selected automatically
<select name="aaa">
<option value="0">select any option</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
Solution 2
Here is some documentation of select: http://www.w3.org/TR/html4/interact/forms.html#h-17.6
Related videos on Youtube
Mike
Updated on June 04, 2022Comments
-
Mike almost 2 years
I have several places in my website where a "combobox" style control is needed. To do this, I've encapsulated the combobox control into a .NET server-side component for re-usability. Some pages may have a combobox on them, some may not.
At the core, this combobox contains a textbox and a "dropdown" aligned appropriately with CSS. Part of the HTML rendered is simply:
<select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select>
The dropdown must start off empty, and changing to any value (including "Option 1") must trigger the onchange event.
I accomplish this by doing something like:
document.getElementById("theSelectElement").selectedIndex = -1;
but I'd prefer not to have to run javascript against each element on the page. I realize that I could use jQuery to select against a CSS class, but most pages won't have a select element on it and nothing will happen.
Is there a way to set selectedIndex that's encapsulated in the tag itself? Something like:
<select selectedIndex="-1">...
or
<select onload="this.selectedIndex = -1">...
?
-
Doozer Blake over 12 yearsCan you not add an empty option as the first one?
-
-
Mike over 12 yearsyeah, but I need the default value to be empty (it's part of how a standard combobox is expected to work)
-
Ghazanfar Mir over 12 yearsthen set the
value
property of the firstoption
as empty. And if you don't need the text either of the first option then go for the @wes asnwwer. -
Mike over 12 yearsthat's true, but not really the point of the question. I'm really asking how the rendered HTML can accomplish the goal of having a blank initial state.