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
/*
*/
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;
}
I tried the code without the parenthesis but the bit of code i'm struggling with is the switch statement. I removed 'length' as variable name in the changeClass() function because i thought it being reserved by javascript might be part of the problem but even with another variable name ('distance') only the default statement is called.
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
The <img> tag is the result of a bug in this forum's software. The character sequence "8)" was incorrectly interpreted as a smiley and replaced with the <img> tag.
// In JavaScript, this
switch (value) {
case (value < 10) :
}
// means
if (value == (value < 10)) {}
// which, if value is less than 10, is the same as
if (value == true) {}
switch (i) {
case 0:
case 1:
case 2:
/* i is 0, 1, or 2 */
break;
case 3:
/* i is 3 */
break;
case 4:
case 5:
/* i is 4 or 5*/
break;
default:
/* i is something else */
break;
}