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

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


当前回答

默认情况下,您可以使用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>

其他回答

是的,它正在工作:

<select name="somename" required>
     <option value="">Please select</option>
     <option value="one">One</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.

必填项:第一个值为空-必填项工作为空值

先决条件:正确的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.

<select>元素支持required属性,按照规范:

http://dev.w3.org/html5/spec-author-view/the-select-element.html#the-select-element

哪个浏览器不支持这个功能?

(当然,无论如何您都必须在服务器上验证,因为您不能保证用户将启用JavaScript。)

你也可以用JQuery动态地做到这一点

设置所需的

$("#select1").attr('required', 'required');

删除需要

$("#select1").removeAttr('required');