Html 如何在没有选择默认值的情况下设置所需的选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25321180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:30:10  来源:igfitidea点击:

how do you set up a required select without a default value selected

htmlhtml-select

提问by Daniel

I'm trying force the user to make a selection, rather than just using the first field. How do I prevent the user from submitting this form without using javascript?

我试图强制用户进行选择,而不仅仅是使用第一个字段。如何防止用户在不使用 javascript 的情况下提交此表单?

<select required>
  <option >Make a selection</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi">Audi</option>
</select> 

回答by ajp15243

Per this answer, you can use HTML5's requiredattribute on a <select>if you give the default <option>an empty valueattribute (among other criteria, see the <select>docs).

这个答案,你可以使用HTML5的required一个属性<select>,如果你给默认<option>的空value属性(其它标准中,看到<select>文档)。

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an optgroup element), then that option is the select element's placeholder label option.

如果 select 元素指定了 required 属性,没有指定 multiple 属性,并且显示大小为 1;如果 select 元素的选项列表(如果有)中的第一个 option 元素的值是空字符串,并且该 option 元素的父节点是 select 元素(而不是 optgroup 元素),则该选项是 select 元素的占位符标签选项。

So you would want

所以你会想要

<select required>
    <option value="">Make a selection</option>
    <!-- more <option>s -->
</select>

Older browsers will need a JavaScript solution, given the fact that they don't support HTML5.

较旧的浏览器将需要 JavaScript 解决方案,因为它们不支持 HTML5。

回答by Mark Ignacio

The HTML5 spec on selectdefines an option with a value of the empty string as a placeholder label option.

上HTML5规范select定义与空字符串作为占位符标签选项的值的选项。

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, and that option element's parent node is the select element (and not an optgroup element), then that option is the select element's placeholder label option.

如果 select 元素指定了 required 属性,没有指定 multiple 属性,并且显示大小为 1;和如果在选项中选择元素的列表(如果有的话)的第一个选项元素的值是空字符串,并且该选项元素的父节点是选择元件(而不是一个OPTGROUP元件),则该选项是选择元素的占位符标签选项。