Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change a text input's value with CSS?

Tags:

css

Is there anyway to change a text input's value (the default text that displays) with CSS?

I'm optimizing a site for mobile and I want the text 'search this site' to be shortened to 'search'.

like image 583
Evanss Avatar asked Oct 06 '11 09:10

Evanss


People also ask

Can CSS change your form data value?

No, CSS cannot change the value attribute of an input , or indeed any attribute of any element.

Can you change text via CSS?

You can replace text through CSS. Let's replace a green button that has the word 'hello' with a red button that has the word 'goodbye', using CSS. Note: We explicitly need to mark this as a block element, 'after' elements are inline by default.

How do you change the input value in CSS?

querySelectorAll('input[type=submit]')[0]. setAttribute("value", "Contact Us");

How do you style text in input tag?

If you only want to style a specific input type, you can use attribute selectors: input[type=text] - will only select text fields. input[type=password] - will only select password fields. input[type=number] - will only select number fields.


1 Answers

That really isn't what CSS is for.

CSS is for styling your content; HTML is for the actual content itself.

If you need to modify the content after the HTML has loaded, then that's what Javascript is for.

So the real answer to your question is: either modify the HTML directly, or use Javascript.

There are some things you can do with CSS that affect the content, such as adding additional text in-front of or behind an element using the :before and :after pseudo-selectors, but that won't help you in this case, and shouldn't be used for the kind of content change work that you're talking about.

By the way, slightly off-topic, but if you're using input field value as a prompt text, you may want to consider looking into the HTML5 placeholder attribute instead. This also doesn't address your question, but it does sound like it might be something that could be useful to you.

like image 139
Spudley Avatar answered Sep 27 '22 20:09

Spudley