//I need to add one to the total each time the error name is input. For example if I type "S" in the prompt, then it will add 1 to the total steering and if I type "W", it will add to wiper. The loop should run until i entered a null or zero value and calculate the total errors.
<html>
<head><title>Charge Calculator</title></head>
<body>
<script type="text/javascript">
//Declaring Variables
var day;
var data="";
var steering = 0;
var turbo =0;
var wiper =0;
day = prompt("Enter day: ","");
var BR="<br/>";
do
{
data = prompt("Enter Data: ","");
data = input.nextLine();
switch(data)
{
case 'S':
steering ;
break;
case 'T':
turbo ;
break;
case 'W':
wiper ;
break;
}
}
while(data == "")
document.write("day: " day BR); //Display destination name
document.write("Steering issue: " steering BR);
document.write("turbo Issue: " turbo BR);
document.write("wiper Issue: " wiper BR);
</script>
</body>
</html>
CodePudding user response:
There are many things to be improved in your code. Be aware that the write()
expression will potentially destroy parts of your html-based page. Find out about DOM manipulation commands instead.
The following snippet demonstrates in a very short way how you could collect your inputs. I used your prompt()
method simply to show that it can be done but I would always prefer a simple input
field instead.
const counts={s:0,t:0,w:0};
while ( counts[prompt("Please enter the error type code (s,t or w):").toLowerCase()]) {}
console.log("steering: " counts.s
"\nturbo: " counts.t
"\nwipers: " counts.w);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Everything happens within the expression that calculates the result for the while
condition: the input value is converted to lower case and then a property of the object counts
will be incremented. This will only work (= return a "truthy" result) for already initialised properties like s
, t
or w
. For all other cases an increment cannot be calculated, resulting in an "NaN" ("not a number") result. This will then end the while loop.
CodePudding user response:
Seems like recursion could be more appropriate solution here. Though @Cartsten's one looks absolutely ok also.
function count() {
const counts = {
s: 0,
t: 0,
w: 0
};
const checkCounts = () => {
let input = prompt(
'Please enter the error type code (s,t or w):'
).toLowerCase();
if (counts[input] !== undefined) {
counts[input];
return checkCounts();
}
};
checkCounts();
console.log(
`steering: ${counts.s} \n turbo: ${counts.t} \n wipers: ${counts.w}`
);
}
count();
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>