我怎么能检查用户是否从HTML5中的<select>字段选择了一些东西?

我看到<select>不支持新的必需属性…我必须使用JavaScript吗?还是我遗漏了什么?:/


当前回答

试试这个

<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>

其他回答

是的,它正在工作:

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

你得把第一选项空着。

首先,您必须在第一个选项中分配空白值。 选择这里。而不是只需要工作。

将选择框的第一项的值设为空白。

所以当你发布表单时,你会得到空白值,使用这种方式,你会知道用户没有从下拉菜单中选择任何东西。

<select name="user_role" required>
    <option value="">-Select-</option>
    <option value="User">User</option>
    <option value="Admin">Admin</option>
</select>

Works perfectly fine if the first option's value is null. Explanation : The HTML5 will read a null value on button submit. If not null (value attribute), the selected value is assumed not to be null hence the validation would have worked i.e by checking if there's been data in the option tag. Therefore it will not produce the validation method. However, i guess the other side becomes clear, if the value attribute is set to null ie (value = "" ), HTML5 will detect an empty value on the first or rather the default selected option thus giving out the validation message. Thanks for asking. Happy to help. Glad to know if i did.

试试这个

<select>
<option value="" style="display:none">Please select</option>
<option value="one">One</option>
</select>