我怎么能检查用户是否从HTML5中的<select>字段选择了一些东西?
我看到<select>不支持新的必需属性…我必须使用JavaScript吗?还是我遗漏了什么?:/
我怎么能检查用户是否从HTML5中的<select>字段选择了一些东西?
我看到<select>不支持新的必需属性…我必须使用JavaScript吗?还是我遗漏了什么?:/
当前回答
首先,您必须在第一个选项中分配空白值。 选择这里。而不是只需要工作。
其他回答
是的,它正在工作:
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
你得把第一选项空着。
你也可以用JQuery动态地做到这一点
设置所需的
$("#select1").attr('required', 'required');
删除需要
$("#select1").removeAttr('required');
必填项:第一个值为空-必填项工作为空值
先决条件:正确的html5 DOCTYPE和命名输入字段
<select name="somename" required>
<option value="">Please select</option>
<option value="one">One</option>
</select>
根据文档(列表和粗体是我的)
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.
首先,您必须在第一个选项中分配空白值。 选择这里。而不是只需要工作。
你需要将option的value属性设置为空字符串:
<select name="status" required>
<option selected disabled value="">what's your status?</option>
<option value="code">coding</option>
<option value="sleep">sleeping</option>
</select>
当用户在表单上按submit键时,Select将向服务器返回所选选项的值。空值与空文本输入相同——>引发所需的消息。
w3schools
value属性指定提交表单时发送到服务器的值。 例子