开发者

Can an HTML <select> element have a default selectedIndex of -1 without running page-wide javascript?

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>Opt开发者_如何转开发ion 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">...

?


a select is a radio state holder so there is no "non-selected" 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 an empty < option >


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>


Here is some documentation of select: http://www.w3.org/TR/html4/interact/forms.html#h-17.6


If you've wrapped it in your own user control or custom control then you'll need to expose the defaultSelection property (or whatever you name it) publicly so it can be specified in your server tag.

You talk about doing it in a <select> tag, but this is the HTML markup - not the server-side markup of <ASP:DropDown ... > or <myControl:CustomSelect ... >

EDIT : If it's pure HTML, then just output the default selection with the selected property set:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜