Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
123 views
in Technique[技术] by (71.8m points)

html - how do you set up a required select without a default value selected

I'm trying force the user to make a selection, rather than just using the first field. How do I prevent the user from submitting this form without using javascript?

<select required>
  <option >Make a selection</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi">Audi</option>
</select> 
question from:https://stackoverflow.com/questions/25321180/how-do-you-set-up-a-required-select-without-a-default-value-selected

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Per this answer, you can use HTML5's required attribute on a <select> if you give the default <option> an empty value attribute (among other criteria, see the <select> docs).

If a select element has a required attribute specified, does not have a multiple attribute specified, and has a display size of 1; and if the value of the first option element in the select element's list of options (if any) is the empty string, 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.

So you would want

<select required>
    <option value="">Make a selection</option>
    <!-- more <option>s -->
</select>

Older browsers will need a JavaScript solution, given the fact that they don't support HTML5.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...