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

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


当前回答

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

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

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

其他回答

<form action="">

<select required>

  <option selected disabled value="">choose</option>
  <option value="red">red</option>
  <option value="yellow">yellow</option>
  <option value="green">green</option>
  <option value="grey">grey</option>

</select>
<input type="submit">
</form>

默认情况下,您可以使用option元素的selected属性来选择一个选项。您可以使用select元素的必需属性来确保用户选择了一些东西。

在Javascript中,你可以检查selectedIndex属性来获得所选选项的索引,或者你可以检查value属性来获得所选选项的值。

根据HTML5规范,selectedIndex“返回第一个选中项的索引(如果有),如果没有选中项则返回−1。value "返回第一个选中项的值(如果有),如果没有选中项则返回空字符串。"如果selectedIndex = -1,那么你知道他们没有选择任何东西。

<button type="button" onclick="displaySelection()">What did I pick?</button>
<script>
    function displaySelection()
    {
        var mySelect = document.getElementById("someSelectElement");
        var mySelection = mySelect.selectedIndex;
        alert(mySelection);
    }
</script>

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.

你需要将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属性指定提交表单时发送到服务器的值。 例子

是的,它正在工作:

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

你得把第一选项空着。