According to HTML5 Features :
The required attribute is a logical attribute. If specified, the user will need to select a value before submitting the form.
Checking restrictions: If an element has its own required attribute specified , and none of the option elements in the list of elements of the selection list has the value set to true, or the only element in the list of elements of the selection list with its value set to true is the label label flag , then this element suffers from absence.
If the value of the element of the first option in the list of selection elements (if any) is an empty string , and this element is a parent node, the select element (and not the optgroup element), then this parameter selects the label label element.
my accent
From the above statements it follows that the select element with the required attribute will become valid only when the user selects a value. Until then, it will remain in an invalid state.
The :valid ,: :invalid pseudo-elements themselves can help to style the select element depending on whether the value was selected or not, but this depends on several factors. They look like this:
- Having selected, you want to check whether a valid value has been selected, and not just any choice.
- An invalid or empty value (in this case, "Select a widget ...") has
value="" and is the first parameter in the select element. - The
select element is a required element - this means we can add the required attribute to it.
Based on your statement of the problem, I think your script satisfies all of the above factors.
select { border: 2px solid blue; outline: none; } select:valid { border: 2px solid green; outline: none; }
<select required> <option value="">Select a widget...</option> <option value="1">Widget 1</option> </select>
The above snippet has been tested in IE10 + (including Edge), Chrome, Opera, and Firefox.
source share