sojim2
sojim2

Reputation: 1307

Change input and textarea background color when there's no value

What's the recommended approach to change the background color of input and textarea when there's no value? Can this only be done on page load or can it be persistent? I prefer if it's persistent since I have a form that loads from callbacks.

I'm thinking JQuery would be best for this to affect this css:

input[type="text"], textarea {
  background-color : #d1d1d1; 
}

I tried this, but only the textarea had the changes for some reason:

input[type="text"]:empty, textarea:empty {
  background-color : #d1d1d1; 
}

DevExpress input textbox:

<input class="dxeEditArea_DevEx dxeEditAreaSys"
 id="ctl00_ctl00_ASPxSplitter1_Content_ContentSplitter_MainContent_ASPxCallbackPanel1_ASPxFormLayout3_ASPxFormLayout3_E18_I" 
name="ctl00$ctl00$ASPxSplitter1$Content$ContentSplitter$MainContent$ASPxCallbackPanel1$ASPxFormLayout3$ASPxFormLayout3_E18" readonly="readonly" 
onfocus="aspxEGotFocus('ctl00_ctl00_ASPxSplitter1_Content_ContentSplitter_MainContent_ASPxCallbackPanel1_ASPxFormLayout3_ASPxFormLayout3_E18')" 
onblur="aspxELostFocus('ctl00_ctl00_ASPxSplitter1_Content_ContentSplitter_MainContent_ASPxCallbackPanel1_ASPxFormLayout3_ASPxFormLayout3_E18')" value="Business" 
type="text" style="background-color: rgb(192, 224, 206);">

I've also tried empty/not empty method and it still doesn't work for some reason. It changes color to gray, but it doesn't change the background to white if it's not empty:

input[type="text"]:empty {
background-color : #d1d1d1; 
}

input[type="text"]:not(:empty) {
background-color : #FFFFFF; 
}

Upvotes: 2

Views: 6261

Answers (3)

adeneo
adeneo

Reputation: 318302

It could be done quite easily with jQuery, cross-browser of course.

$(':input').on('input', function() {
    $(this).toggleClass('empty', this.value.length === 0);
}).trigger('input');
input.empty, textarea.empty {
  background-color : #d1d1d1; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input />

Upvotes: 4

dippas
dippas

Reputation: 60573

you can use Attribute Selector for placeholder in input and textarea or for value in input and :focus :

[placeholder=""],
[value=""] {
  background: red;
}
[placeholder=""]:focus,
[value=""]:focus {
  background: none
}
<h2>Placeholder</h2>
<input type="text" placeholder="" />
<textarea placeholder=""></textarea>
<hr />
<h2>Value</h2>
<input type="text" value="" />

Upvotes: 1

G-Cyrillus
G-Cyrillus

Reputation: 106008

You might need the attribute required and the selector :invalid

input[type="text"]:invalid, textarea:invalid {
  background-color : #d1d1d1; 
}
<input required type="text" placeholder="write here"/>
<textarea required placeholder="write here"></textarea>
<hr/>
<input required type="text" placeholder="write here" value="text"/>
<textarea required placeholder="write here">text</textarea>

Upvotes: 5

Related Questions