5

I am designing a form using bootstrap that has 3 states.

  1. The initial unfilled out state
  2. The focused state
  3. A filled out state (ex user types something in a text box)

I am currently having trouble differentiating states #1 and #3. Is this possible to do without javascript?

  • I don't think you can differentiate 1 & 3 using [pure css](http://stackoverflow.com/questions/16952526/detect-if-an-input-has-text-in-it-using-css). – wahwahwah Jun 08 '15 at 14:58
  • I'd like to see if there's an answer for this too. I know of ::hover, ::active, ::focus, ::link. ::empty might work on input fields like textboxes but not all input fields. If you're using some form of unobtrusive validation which does add classes for you, could you not use them? – Jacques Jun 08 '15 at 14:58
  • It looks like there are some features in [HTML5 / CSS3 that might be of use](http://webdesign.tutsplus.com/tutorials/bring-your-forms-up-to-date-with-css3-and-html5-validation--webdesign-4738) If you're looking for strict browser compat and consistency, I'd say the answer is "no - you need javascript." – wahwahwah Jun 08 '15 at 15:03

1 Answers1

6

There is currently no CSS that differentiates between "empty" and "not empty" (unless you use Javascript on every keystroke that copies the content to the value attribute).

However, there is the :valid pseudoclass which you can use. If you don't mind requiring the user to enter something in the textbox, you can add the required attribute, and then a non-empty value will be valid!

input {background:white} /* empty state */

input:valid {background:yellow} /* has content typed in */
<input required>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
  • Doesn't `pattern=".*"` actually imply that zero or more characters are allowed? Should this be `pattern=".+"` which is one more more characters? Of course, the required attribute makes sure that at least one character is entered, but still I assume it would be better to update the regex accordingly? – user2019515 Nov 06 '17 at 23:59
  • @user2019515 Hm, you're right. In this particular example, you can even omit the pattern attribute entirely and it will work in the same way. So I'm not sure why I did that! – Mr Lister Nov 07 '17 at 07:25
  • It's possible that I assumed `pattern=".*"` would mean that an empty value would also be considered OK, since the OP didn't say that the value would have to be required. But I can't really remember. Anyway, that isn't the case, so, never mind. – Mr Lister Nov 07 '17 at 07:26