Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>  
like image 620
Daniel Avatar asked Aug 15 '14 04:08

Daniel


People also ask

How do I set the default value in select?

The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute. The option that is having the 'selected' attribute will be displayed by default on the dropdown list.

How do you pre select a select option?

The selected attribute is a boolean attribute. When present, it specifies that an option should be pre-selected when the page loads. The pre-selected option will be displayed first in the drop-down list. Tip: The selected attribute can also be set after the page loads, with a JavaScript.


1 Answers

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.

like image 132
ajp15243 Avatar answered Oct 05 '22 22:10

ajp15243