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

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


当前回答

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中,你可以使用完整的表达式:

<select required="required">

我不知道为什么简短的表达不管用,但是试试这个。 这就解决了。

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

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

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

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

是的,它正在工作:

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

你得把第一选项空着。

试试这个,这个会有用的,我试过了,这个有用。

<!DOCTYPE html>
<html>
<body>

<form action="#">
<select required>
  <option value="">None</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
<input type="submit">
</form>

</body>
</html>

试试这个

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