Is there a way to target all textareas with a valu

2020-03-28 22:19发布

问题:

I imagined this to be straightforward, but I am unable to find anything that indicates I can use CSS to target non-empty textareas on a page.

I'm okay with JS if CSS absolutely does not support this, but even with jQuery I can't find a way to use a selector, but have to explicitly check for a .val().

Some context: I have an optional textarea that expands on focus, but if the user does decide to type something, I don't want it to shrink again when focus leaves.

回答1:

Markup-wise, the :empty selector should allow you to select textareas that have absolutely no content, not even so much as whitespace or a line break. Conversely :not(:empty) should let you select non-empty textareas.

Selectors in CSS are mostly static though, meaning they don't account for dynamic changes such as if you edit a textarea's content after page load. Furthermore, a selector like :empty doesn't really account for a textarea's value so much as it checks for the presence (or absence) of content nodes in general, so I suspect it doesn't play well with forms.

If you need to apply styles dynamically based on the value of a form field, you'll need to use a script to check its value using .val() or something similar every time it updates.



回答2:

Yes, you can do it in jQuery like:

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

DEMO HERE



回答3:

Look at :invalid & :valid CSS3 pseudo classes:

DEMO

<textarea required="required"></textarea>

textarea:invalid{background:red}
textarea:valid{background:blue}


回答4:

How about using .filter()?

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


回答5:

$('textarea:empty') is a nice way of doing it, but as I am dealing with textareas whose content may constantly change and be empty at one point and non-empty the next, this would still require checking every time the user focuses in and out of the textarea.

I ended up adding a class .empty to my textarea, and checking its value every time .focusout is fired:

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

This way I can keep the styling in my stylesheets and the rules defined by .empty get used even after the user has typed something and decides to delete it all.