Is there a way to target all text areas with a value using only CSS?

I assumed it was simple, but I canโ€™t find anything that indicates that I can use CSS to target non-empty text fields to a page.

I'm fine with JS if CSS absolutely doesn't support this, but even with jQuery I can't find a way to use the selector, but I have to explicitly check for the presence of .val ().

In some context: I have an optional text area that expands in focus, but if the user decides to type something, I donโ€™t want it to contract again when the focus is gone.

+2
jquery css css-selectors textarea
source share
5 answers

$('textarea:empty') is a good way to do this, but since I am dealing with text fields whose contents can constantly change and be empty at one point and non-empty next, it still needs to be checked every time the user focuses and from the text box.

As a result, I added the .empty class to my text box and each time I check its .focusout value:

 $('textarea').focusout(function() { if ($(this).val() == '') { $(this).addClass('empty'); } else { $(this).removeClass('empty'); } }); 

This way I can save the style in my stylesheets, and the rules defined by .empty will be used even after the user has typed something and decides to delete it all.

+1
source share

Markup, selector :empty should allow you to select text areas that have absolutely no content, not even like a space or line break. And vice versa :not(:empty) should allow you to select non-empty text fields.

CSS selectors are mostly static, that is, they do not take into account dynamic changes, for example, if you edit the contents of the text field after loading the page. In addition, a selector like :empty does not really take into account the value of textarea, since it checks for the presence (or absence) of content nodes in general, so I suspect it does not work very well with forms.

If you need to dynamically apply styles depending on the value of the form field, you will need to use a script to check its value with .val() or something similar with each update.

+3
source share

Yes, you can do it in jQuery, for example:

 $('textarea:not(:empty)').css('color','red'); 

DEMO HERE

+1
source share

Take a look at :invalid & :valid CSS3 pseudo-classes:

Demo

 <textarea required="required"></textarea> textarea:invalid{background:red} textarea:valid{background:blue} 
+1
source share

How about using .filter() ?

  $("input").filter(function() { return this.value == ""; }).css('dosomething'); 
+1
source share

All Articles