开发者

Can I select empty textareas with CSS?

Is there a way that I can select a textarea such that $('#id_of_textarea').val() in jQuery will be ''? I tried using :empty. I saw that CSS provides a way to select empty inputs because the text is in the value at开发者_StackOverflow中文版tribute ([value=""]). Is there an attribute for the text in a textarea?

I'm looking for a selector that will work with CSS, not just jQuery.


Best solution I can think of is a CSS 3 workaround. Set the field to required (and unset it on submit if need be). Then you can use

textarea:invalid { /* style here... probably want to remove box-shadow and such */ }


this works in recent browsers except edge (at the moment):

textarea:placeholder-shown {
  /* this should be active only when area is empty and placeholder shown */
}

so with jQuery for example you can pick all empty textareas:

$('textarea:placeholder-shown').val()

https://developer.mozilla.org/en/docs/Web/CSS/:placeholder-shown


If you're using React, then this is the solution:

textarea:not(:empty) {

 // Apply css here

}

For instance,

/* Apply style when textarea contains text */

textarea:not(:empty) {
  border: 6px solid blue;
  padding: 6px;
}

Working demo: Textarea - Select empty textarea using CSS

Note: While this works perfectly in React (because of re-painting caused by state update), It does not provide the same response if implemented using Vanilla HTML + CSS.


This works fine, as with input:

<textarea name="comment" id="comment" class="authority_body-input" data-val="{$form.comment}" onkeyup="this.setAttribute('data-val', this.value);">

textarea.authority_body-input:not([data-val=""]):not(:focus) {
    color: red;
}


You can use the :empty css pseudo-class.

See an example in jsfiddle.

In the example there is a button for dynamically add new empty textareas to the DOM, so you can see that the new elements also are affected with the pseudo-class.

The code in the example was tested in Firefox 5.0, Opera 11.50 and Chromium 12.

Also, you can see a good description for the :empty pseudo-class here.


For those who are using AngularJS, you can use ng-class in your view to add a class to your textarea to know if it is empty or not.

HTML :

<textarea ng-model="myForm.myTextArea"
          ng-class="(myForm.myTextArea.length)?'not_empty':'empty'">
</textarea>

CSS :

textarea.empty {
    background-color:red;
}
textarea.not_empty {
    background-color:blue;
}

Here is a jsfiddle.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜