user1953045
user1953045

Reputation: 306

How to change bordercolor based on value of textbox? using javascript

I have a textbox which has a red border as default.

when on focus, (:focus) the border turns green.

When there is 1 or more characters in the textbox, the border turns blue (using this js)

function CheckText()

{

    var elem = document.getElementById('sendto');

    if(elem)

      {      
      if(elem.value.length != 0)
      elem.style.borderColor = '#3366CC';
      }

}

the problem I have is, if I delete all the characters from the box after it has turned blue, it stays blue and does not return to red. the :focus green does not work anymore either after typing in the cell.

Can anyone help?

this is the HTML code for my box:

<input id="sendto" name="sendto" type="text" class="sendsubempty" onBlur="CheckText()" value="<? 
  if(!$sendto){ 
  echo"";
  }else{
  echo"$sendto";
  }
  ?>" maxlength="50" />

for info: class- sendsubempty has a red border.

I have seperate classes for blue & green borders if its easier to use in the javascript.

Please help :(

Upvotes: 1

Views: 7572

Answers (3)

Benjamin Toueg
Benjamin Toueg

Reputation: 10867

I agree with Loris. But it's not completely correct.

function CheckText()

{

    var elem = document.getElementById('sendto');

    if(elem)
    {      
      if(elem.value.length === 0)
      {
        elem.style.borderColor="";
      }
      else{
        elem.style.borderColor="#3366CC";
      }
    }

}

Here is the jsbin : http://jsbin.com/welcome/70238/edit

Upvotes: 1

user625860
user625860

Reputation:

Here is a more elegant way to achieve this effect:

http://jsfiddle.net/elias94xx/eqKqS/

HTML

<textarea id="test"></textarea>

CSS

#test { border-color: red; }
#test:focus { border-color: green !important; outline: none; }

JS

document.getElementById("test").addEventListener("keydown", controlBorderColor, false);
document.getElementById("test").addEventListener("keyup", controlBorderColor, false);

function controlBorderColor() {
  if (this.value.length == 0) { this.style.borderColor = "red"; }
  else { this.style.borderColor = "blue"; }
}

Upvotes: 1

Loris
Loris

Reputation: 1

The function CheckText should be changed from:

  {      
      if(elem.value.length == 0)
      elem.style.borderColor = '#3366CC';
  }

to:

  {
    if(elem.value.length){ elem.style.borderColor=""; }
    else{ elem.style.borderColor="#36c"; }
  }

Upvotes: 0

Related Questions