0

Is there any css property which can be used to highlight all the filled fields? Just like we have, on focus css properties.

input[type="text"] {
  background-color: white;
}
input[type="text"]:focus {
  background-color: red;
}
<input type="text">

I want to make the field background-color green when there is something in the field. Is this possible through CSS? If not CSS, is there any other way?

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • 1
    There is no selector in CSS which does this. You'll need Javascript. http://stackoverflow.com/questions/3617020/matching-an-empty-input-box-using-css – Hunter Turner Jul 12 '16 at 16:34
  • You may find your answer here : http://stackoverflow.com/a/16957328/6044997 – Damien Jul 12 '16 at 16:37
  • 1
    Dammit @Oriol, I was 90% of the way through writing a vitriolic rant about the OP trying to sidestep putting his code in his question when you had to go and do the productive thing and add it for him. ;) – j08691 Jul 12 '16 at 16:52
  • 1
    Yeah, I was considering writing a rant too... – Oriol Jul 12 '16 at 16:54

2 Answers2

0

Certainly you can achieve this with javascript.

The script below will listen for a keyup after the focus has shifted to any one of the <input> fields.

It will then check to see if the respective <input> field is empty.

If it is not, it will change the background of the <input> field to green.

var inputs = document.querySelectorAll('input[type="text"]');

function detectContent() {
    if (this.value !== '') {
        this.style.backgroundColor = 'green';
        this.style.color = 'white';
    } else {
        this.style.backgroundColor = 'white';
        this.style.color = 'black';
    }
}


for (var i = 0; i < inputs.length; i++) {
    var input = inputs[i];
    input.addEventListener('keyup', detectContent, false);
}
<input type="text" />

<input type="text" />

<input type="text" />
Rounin
  • 27,134
  • 9
  • 83
  • 108
0

Try this...

$(document).ready(function() {
  $(':input').on('input', function() {
    if (this.value.length > 0) {
      $(this).css('background-color', 'green');
    } else {
      $(this).css('background-color', '');
    }
  });
});
input[type="text"] {
  background-color: white;
  color: #fff;
}
input[type="text"]:focus {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text">
<input type="text">
<input type="text">
<input type="text">
Rahul K
  • 888
  • 5
  • 16