Can an HTML <select> element have selectedIndex of -1 by default without running JavaScript on the entire page?

I have several places on my website where combobox style management is required. To do this, I encapsulated the combobox control in a server-side .NET component for reuse. Some pages may have a combo box, and some may not.

In the kernel itself, this combo box contains a text box and a drop-down menu aligned appropriately with CSS. Part of the processed HTML is simple:

<select> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select> 

The popup menu should start from scratch, and changing any value (including "Option 1") should trigger an onchange event.

I accomplish this by doing something like:

 document.getElementById("theSelectElement").selectedIndex = -1; 

but I would prefer not to run javascript for every element on the page. I understand that I could use jQuery to select against the CSS class, but most pages on it will not have a select element and nothing will happen.

Is there any way to set selectedIndex enclosed in the tag itself? Sort of:

 <select selectedIndex="-1">... 

or

 <select onload="this.selectedIndex = -1">... 

?

+4
source share
4 answers

a choice is the holder of a radio state, so there is no โ€œunselectedโ€ state

 <select name="aaa"> <option value=""></option> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> <option>Option 4</option> </select> 

btw you can use empty <option>

+2
source

You can 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> 
+2
source

The documentation below is optional: http://www.w3.org/TR/html4/interact/forms.html#h-17.6

+1
source

If you wrapped it in your own user control or user control, you will need to publish the defaultSelection property (or whatever you call it) publicly so that it can be specified in the server tag.

You say this in the <select> , but this is HTML markup, not server side markup <ASP:DropDown ... > or <myControl:CustomSelect ... >

EDIT: If this is pure HTML, just enter the default value using the selected property:

 <select> <option value="1">Top</option> <option selected="selected" value="-1">Middle (Empty)</option> <option value="2">End</option> </select> 
-1
source

All Articles