Change border of input colour when user types

Hi there,

I trying to get a form’s inputs to become and stay green when a user starts to type…and with little knowledge this is what i’ve got, with no luck…

//onload event
window.onload = function(){

 var elements = document.getElementsByClassName("quantity");
    for(var i = 0, length = elements.length; i < length; i++) {
       if(this.value != '') { elements[i].style.borderColor = "green";}
          elements[i].sstyle.borderColor = "blue" ;

Any pointers would be great…

Why use JS? Why not just use CSS (:focus)?

However, there is a typo in your JS:


yeah, i’ve sorted the typo…using CSS i can only style when its active or focus if i had to go to the next input the colour will revert back…where i want javascript to see the input isn’t empty and apply the border colour, and if its empty apply the colour change to indicate it needs to have content in it.

1 Like

input:placeholder-shown { border-color: green; }

CSS has advanced to the point of being able to detect this :wink:


You can also style using :valid and invalid assuming you have the required attribute in place.

e.g. Rough example.

It’s not perfect because all inputs are basically invalid to start with.

The placeholder shown trick that @m_hutley mentioned can be found here along with other examples.


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.