ccmanz
ccmanz

Reputation: 181

Add Background color after setting content in input field

Is there any way that i could add a background color after placing a content inside an input field? Just like what happens when an autocomplete works.

Thanks!

Upvotes: 0

Views: 1372

Answers (5)

Shaggy
Shaggy

Reputation: 6796

There are a few ways you could achieve this. You could make the input mandatory by adding the required attribute. Doing this means that as soon as the user enters anything into the field, it is now in the valid state and you can target it in your CSS using the :valid pseudo-class:

input:valid{
  background:#ff9;
}
<input required>

Or, if you don't want to make the field mandatory and as others have suggested, you could set the new background-color when the field receives focus. To prevent it from reverting to its initial color when it loses focus, you will need to add a transition to the background, setting the transition-delay to some ridiculously high number when the input is in its normal state and resetting it to 0s when it is focused. Obviously, though, this change will occur whether or not the user actually enters anything in the field or not.

input{
  transition-delay:9999s;
  transition-property:background;
}
input:focus{
  background:#ff9;
  transition-delay:0s;
}
<input>

If neither of those options suit your needs then you will probably need to resort to using JavaScript to add or remove a class, depending on whether or not the value of the input is empty.

document.querySelector("input").addEventListener("input",function(){
  this.value?this.classList.add("filled"):this.classList.remove("filled");
},0);
.filled{
  background:#ff9;
}
<input>

Upvotes: 1

Naga
Naga

Reputation: 2168

Using Jquery,

$( "#target" ).blur(function() {
    $( "#target" ).css('background-color','red');
});

DEMO

Upvotes: 0

bhanu.cs
bhanu.cs

Reputation: 1365

Add a Css class like

.myCSSClass
{
background-color:red;
}

Now using jquery on blur function you add this class

$("#myTextBox").on('blur',function(){
if($("#myTextBox").val()==""){
  if($("#myTextBox").hasClass("myCSSClass")){
    $("#myTextBox").removeClass("myCSSClass");
  }
}
else
{
$("#myTextBox").addClass("myCSSClass")
}
});

Upvotes: 0

Luthando Ntsekwa
Luthando Ntsekwa

Reputation: 4218

Here is a solution with pure javascript

var input = document.getElementById("test");
input.addEventListener('input', function() {
  if (input.value)
    input.style.backgroundColor = '#90EE90';
  else
    input.style.backgroundColor = '#fff';
});
<input id="test" type="text" value="">

Upvotes: 0

Sumit patel
Sumit patel

Reputation: 3903

Html

First name: <input type="text" name="firstname">

Css

 input:focus {
        background-color: yellow;
    }

Demo in JsFiddle

Upvotes: 0

Related Questions