Reputation: 17
When I test a string using the inputName function, I get stuck in an infinite loop that keeps displaying the alert() functions in the browser. I'm not sure the logic behind why it's happening. Note this is for a school assignment and I'm required to use a for loop and a function with parameters to test inputted data called employeeName. The function tests to see if the data is null, empty or a number before returning a value.
<html>
<head>
<script type="text/javascript">
function inputName(name)
{
var flag;
do
{
flag = false;
if (name == null)
{
alert("You have hit the 'Cancel' button!");
return name;
flag = false;
}
if (name == "")
{
alert("You tried entering no name!");
flag = true;
}
else if (!isNaN(name))
{
alert("You tried entering a number!");
flag = true;
}
else if (name.length < 2)
{
alert("You tried entering a name less than 2 characters!");
flag = true;
}
} while (flag);
return name;
}
</script>
</head>
<body>
<script type="text/javascript">
// DECLARATIONS
var numEmployees;
var employeeName;
var testName;
// INPUT
numEmployees = prompt("Enter the number of employees");
// PROCESSING
for (var index = 1; index <= numEmployees; index++)
{
employeeName = prompt("Enter a name.");
testName = inputName(employeeName);
}
// OUTPUT
</script>
</body>
</html>
Upvotes: 0
Views: 333
Reputation: 21275
You need to prompt the user to correct the name.
var getName = function() {
var name;
do {
name = prompt("Enter a name.");
} while(!validateName(name));
return name;
};
var validateName = function(name) {
if (name == null) {
alert("You have hit the 'Cancel' button!");
return true;
}
if (name == "") {
alert("You tried entering no name!");
return false;
}
else if (!isNaN(name)) {
alert("You tried entering a number!");
return false;
}
else if (name.length < 2) {
alert("You tried entering a name less than 2 characters!");
return false;
}
return true;
};
Upvotes: 0
Reputation: 207557
Because you are not prompting for a new name inside of the loop, the name never changes so you keep testing the same string over and over again.
Upvotes: 2
Reputation: 414006
You're not using a for
loop; that's a do ... while
loop.
The problem is that you set "flag" to true
, but nothing happens to set it to false
before you loop around and set it to true
again. If the function starts off with the "name" being empty, a number, or a single-character string, that loop will just go on and on.
Upvotes: 1