CSS selector for SELECT html element with nothing selected
Asked Answered
E

2

6

I know I used the word select a lot there... sorry.

Anyway, I am looking for a CSS Selector that I can use to identify HTML Select elements on a page that do not have a selection made yet so that I can highlight them for the user to know those elements still need to be completed. I do have an empty option as the first element in the select, so if that helps... please use it.

My stupid attempts thus far: select:empty select[selectedIndex="0"]

<select>
  <option value="" />
  <option value="real selection" />
<select>

So essentially, I want to find all the selects where an option hasn't been selected, the value of the selection is 0, or the index of the selection is 0. (these are equivalent in my scenario). This way I can highlight those on my screen to let the user know, "hey, you've got more work to do."

FYI: Psuedo and CSS3 selectors are just fine for this scenario too.

Edmondo answered 11/7, 2013 at 15:30 Comment(0)
M
1

UPDATE 2024

You can now use select:has( option[value=""]:checked ) to eg. style select with default empty value as a placeholder with grey color, etc...

Moffat answered 23/10, 2024 at 11:27 Comment(0)
T
0

This isn't possible in CSS 3.

When Selectors Level 4 is supported (assuming this bit doesn't change) you can determine the subject of the selector to be other than the last item in the selector and:

select {
    /* Default. Put non-selected styles here */
}

!select > option + option:checked {
    /* An option following another option (so not the first option) is selected */
}

You'd need to make the selectors more complex if you have optgroup elements to deal with.

Trabue answered 11/7, 2013 at 15:34 Comment(1)
There is a bit from the latest draft that excludes ! from use with CSS; if that doesn't change then this may no longer be an option.Ehrlich

© 2022 - 2025 — McMap. All rights reserved.