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.

3 Answers 3

12

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; }
Sign up to request clarification or add additional context in comments.

4 Comments

If you're writing in XML syntax, you'll want to expand that attribute to required="required"...
why would I want to force the required attribute just for that? this is not a good solution
@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.
also the input's type has to be "text" or else probably this won't work as intended
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.

2 Comments

Ah well, I was hoping to keep appearance confined to stylesheets. Thanks for the script, and the js tool.
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.
1

This is possible by using CSS only.

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

More details here.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.