CSS pseudo-selector similar to: valid or: checked for tag selection?

I am trying to find a non-JavaScript way of styling a select tag if it has a value that has been selected.

For example, if I have the following tag:

 <select> <option value="">Select a widget...</option> <option value="1">Widget 1</option> </select> 

Is there a CSS selector that I can use to indicate when the value of this select tag is not empty?

+5
source share
1 answer

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.

+3
source

Source: https://habr.com/ru/post/1241174/


All Articles