You need to use colors that will be noticable. Setting a white background on an element that, by default, has a white background isn't going to do that.
Also, your CSS sets the text color to red all the time, not just when the field is empty.
Additionally (and not part of your issue directly), don't use inline HTML event attributes (onclick
, oninput
, etc.). There are many reasons not to use this old technique that just won't go away. Do all your event binding with modern standards-based code in JavaScript.
Lastly, it's much simpler and more scalable to apply and remove classes to elements than to set individual styles. That can be done easily with .classList.add
, .classList.remove
and classList.toggle
.
Try something like this:
// Get your reference to the element you want to work with:
var input = document.querySelector(".validate");
// Set up the event handler(s). In this case, we want the field
// to undergo validation as the user enters data or if the user
// leaves the field
input.addEventListener("input", validateInput);
input.addEventListener("blur", validateInput);
function validateInput() {
if (input.value === '') {
input.classList.add("invalid");
input.classList.remove("valid");
} else {
input.classList.remove("invalid");
input.classList.add("valid");
}
}
.invalid {
color: red;
background-color:yellow;
}
.valid {
color: blue;
background-color:aliceblue;
}
<p>Type in the box, then backspace out all the data or just click in the box without typing and hit TAB</p>
<input class="validate">