Switch statement in javascript.
Posted: Sat Jul 16, 2011 2:53 pm
I've coded this with the following in mind: A certain length value will change the class of an element. If you enter 8 characters, the background of the box will be green and display the amount of charaters, etc. The current example works perfectly. However if i try something like the commented switch statement, only the default statement is executed. Thanks in advance
Code: Select all
/*
*/
function changeClass(length)
{
var theElement = document.getElementById('box'); // element where innerHTML goes
switch(length)
{
case(1):
theElement.setAttribute("class", "green");
break;
case(2):
theElement.setAttribute("class", "yellow");
break;
case(3):
theElement.setAttribute("class", "red");
break;
default:
theElement.setAttribute("class", "plain");
break;
}
/* // in this example only the default statement executes
case(length >= 8):
theElement.setAttribute("class", "green");
break;
case(length < 8):
theElement.setAttribute("class", "yellow");
break;
case(length <= 5):
theElement.setAttribute("class", "red");
break;
default:
theElement.setAttribute("class", "plain");
break;
*/
}
/*
*/
function showData(inputId, htmlId)
{
var theElement = document.getElementById(inputId); // element to check
var theValue = theElement.value; // value of the element to check
var theHtmlElement = document.getElementById(htmlId); // element where innerHTML is to be written
var theLength = theValue.length; // length of data entered
changeClass(theValue.length);
theHtmlElement.innerHTML = theValue.length;
}
Code: Select all
<form action="" method="post" >
<input type="text" id="inputField" name="password" size="30" onblur="showData('inputField', 'box');" />
</form>
<div id="box" class=""></div>