javascript - 我可以将 required 属性应用于 HTML5 中的 <select> 字段吗?

标签 javascript html select required

如何检查用户是否从 <select> 中选择了某些内容HTML5 中的字段?

我看到 <select>不支持新的 required属性...那我必须使用 JavaScript 吗?还是我缺少什么? :/

最佳答案

强制:将第一个值留空 - 要求对空值起作用

先决条件:正确的 html5 DOCTYPE 和命名输入字段

<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>

根据 the documentation (列表和粗体是我的)

The required attribute is a boolean attribute.
When specified, the user will be required to select a value before submitting the form.

If a select element

  • has a required attribute specified,
  • does not have a multiple attribute specified,
  • and has a display size of 1 (do not have SIZE=2 or more - omit it if not needed);
  • and if the value of the first option element in the select element's list of options (if any) is the empty string (i.e. present as value=""),
  • 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.

关于javascript - 我可以将 required 属性应用于 HTML5 中的 <select> 字段吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6048710/

相关文章:

javascript - 如何计算 <li> 相对于其父容器的 offset()

javascript - 无法在html中显示json数据

javascript - 这在粗箭头函数中未定义,但在封闭范围内定义

html - 使用 Flexbox 垂直居中 div

java - 如何知道 JCalendar 是否为空?

javascript - 如何添加 Croppie 结果上传 php 并将结果传递到其他 php 页面

html - Angular 生成的 css 破坏了子组合器

html - Bootstrap 代码不工作 : Row & Col, 复选框垂直显示

mySQL:选择 * 结合 UNIX_TIMESTAMP

mysql - 通过 "Last Week"、 "Last Month"和 "Last Year"搜索记录的选择查询可能是什么?