What values can appear in the "selected" attribute of the "option" tag?

I have some markup similar to the following:

<select>
  <option selected="selected">Apple</option>
  <option selected="">Orange</option>
</select>

In this case, "Orange" shows as the selected item. I would have expected making the selected attribute blank would undo its effects. Is there a way to write this without simply leaving the attribute out?


Different browser may treat this attribute differently. According to the MSDN documentation (for Internet Explorer):

To select an item in HTML, it is not necessary to set the value of the SELECTED attribute to true. The mere presence of the SELECTED attribute set its value to true.

In firefox and Safari this does work:

<option selected='false' />

From what I can tell by looking at the official WC3 standard for HTML4, the supported case is only:

<option selected='selected' />

You will either need to selectively emit the attribute, or use javascript to control which item is initially selected.


HTML5 spec

https://www.w3.org/TR/html51/sec-forms.html#the-option-element

The selected content attribute is a boolean attribute.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion

The following are valid, equivalent and true :

<option selected />
<option selected="" />
<option selected="selected" />
<option selected="SeLeCtEd" />

The following are invalid :

<option selected="0" />
<option selected="1" />
<option selected="false" />
<option selected="true" />

The absence of the attribute is the only valid syntax for false :

<option />

Recommendation

If you care about writing valid XHTML, use selected="selected" , since <option selected> is invalid and other alternatives are less readable. Else, just use <option selected> as it is shorter.


XHTML中所选属性的唯一允许值是“ 选中 ”的,所以如果您希望您的标记符合XHTML标准,并且跨所有浏览器工作,则只有这样才能使其不被选中

链接地址: http://www.djcxy.com/p/56032.html

上一篇: 让页面告诉浏览器不要缓存/保存输入值

下一篇: “选项”标签的“selected”属性中可以显示哪些值?