select input with empty value using css
HI guys, I want to select an input element which is empty by using css. I tried
:valid
and required
attribute. But the field is optional, I wonder is there other ways to select the input with empty value?
22 Replies
[value=""] should do the trick
also, add :not([value]) in case the attribute doesnt exist at all too
that won't update if someone fills a value in
so, your selector could be something like:
div:has(input[value=""], input:not([value]))
š¤ i have an ideathe best solution is probably a
change
event in javascript
there's a :blank
selector, but it's only a proposal and not super likely to have good support any time soon (it's 0% right now)div:has(input[value=""]:invalid, input:not([value]):invalid)
wait a minute
are you trying to style the parent to show an error/success?I want to style the p element
Your best bet is JavaScript https://codepen.io/jochemm/pen/yLmVKmj
why dont you use
input:user-invalid + p
?
with the required
attribute?the fields are optional
š¤ forgot that detail
so, wait a second
the field is optional but you want to match it when it is empty?
Also, just to clarify from your original,
:empty
is only empty in the sense of the DOM. It selects elements without any child elements, which includes text nodes. It has nothing to do with form elementsjust a clarification: :empty now is supposed to ignore whitespace-only text nodes
also, i solved the problem
set the
pattern
property to [^\s\S]{0}
, and use :user-invalid
to style the p
you will have to hide the validation errors and submit the form in js, but it should work
wait, thats a terrible solution...
š¤ let me brian moreI'd say it's much better to apply the (non-critical) styles with JS, rather than replacing a critical function like submitting with JS
I FOUND A SOLUTION!!!!
:placeholder-shown
if there is placeholder text, and the input doesnt have a value, it selects the inout
inout
input
supported since chrome 47, from 2015
https://jsfiddle.net/ue9np4mk
as soon as you type anything, the <p> loses the blue color
also, the placeholder can be just a space, if you dont want to show anything
https://codepen.io/jochemm/pen/LYwbmyV Works like a charm, even with an empty placeholder
and it works the same
on firefox at least
you just have to have a placeholder attribute
i would put a space, just to avoid weirdness
yup
i knew there was a solution!
good find!
thank you
Thanks guy. It works perfectly
you're welcome
just keep in mind that this is a slightly unintended use of the selector, so, i wont promise it will work forever