7

For instance, a freshly loaded form contains an <input type="text"> which has a green background colour. Once the user enters a value into the field, I would like it to be coloured blue instead.

Is it possible to accomplish this purely using CSS? I understand there is the input[type='text'][value] selector. However, this does not reflect any changes to the form made by the user after it has finished loading, so if the form loaded with no value, it would remain unchanged regardless of what the user does.

Alkenrinnstet
  • 124
  • 2
  • 10

3 Answers3

11

You could give the textfield the required attribute:

<input type="text" required />

and then check for validity with CSS:

input:invalid { background: green; }

or the opposite (only different for old browsers):

input:valid { background: blue; }
Rudie
  • 52,220
  • 42
  • 131
  • 173
  • If you're writing in XML syntax, you'll want to expand that attribute to `required="required"`... – BoltClock Jan 01 '12 at 19:58
  • why would I want to force the required attribute just for that? this is not a good solution – vsync Aug 30 '13 at 18:31
  • @vsync If the field isn't required, I agree. For purely styling, it's not a good solution. If the field is required, it is. – Rudie Aug 30 '13 at 22:31
  • also the input's type has to be "text" or else probably this won't work as intended – vsync Aug 31 '13 at 10:13
1

You can only do this using JavaScript. Here's an example that uses jQuery.

If you want to change the background-color on focus only, you can use the aptly named :focus pseudo-selector. Here's an example of this.

Josh Smith
  • 14,674
  • 18
  • 72
  • 118
  • 1
    Ah well, I was hoping to keep appearance confined to stylesheets. Thanks for the script, and the js tool. – Alkenrinnstet Dec 29 '11 at 16:16
  • 1
    Sure. `:focus` is a decent pseudo-selector that will do much of what you want, but we're used to so much customization now that relies heavily on JS. C'est la vie. – Josh Smith Dec 29 '11 at 16:19
0

This is possible by using CSS only.

  input:placeholder-shown{
    background:#cacaca;
  }

More details here.

iSafa
  • 165
  • 1
  • 8