Creating an input form with javascript - javascript

I had a question about creating a form that I can input "grades" into which also would check to see if those grades were between 0 and 25 or 0 and 100 (input validation). My code has to be in javascript but I don't know where or how to start. In other words, I need to take this code and add a "form" and check for valid input. This is what I have so far:
<!doctype html>
<html>
<script>
var a1=parseFloat(prompt("Enter the grade for assignment 1: "));
var a2=parseFloat(prompt("Enter the grade for assignment 2: "));
var a3=parseFloat(prompt("Enter the grade for assignment 3: "));
var a4=parseFloat(prompt("Enter the grade for assignment 4: "));
var mid=parseFloat(prompt("Enter the grade for the mid exam: "));
var fe=parseFloat(prompt("Enter the grade for the final exam: "));
var fp=parseFloat(prompt("Enter the grade for the final project: "));
var sum;
var grade;
var error;
sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
/* if (a1 < 0 && a1 > 25) {
error = window.prompt( "Assignments are only out of 25 points, please re-enter the integer grade:")
} */
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.writeln("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
</script>
</html>

Take the values from textboxes and give a button get Results and display the result in the output div.
Here is how I have done.
In javascript, take values from the textboxes using document.getElementById("<ID>").value and store it in a variable. Follow the same step for all the input boxes. And process the values obtained from textboxes and display it when the button is clicked.
Here is a simple code snippet which does the same thing using fields.
function myFunction()
{
var a1 = parseFloat(document.getElementById("a1").value);
var a2 = parseFloat(document.getElementById("a2").value);
var a3 = parseFloat(document.getElementById("a3").value);
var a4 = parseFloat(document.getElementById("a4").value);
var mid = parseFloat(document.getElementById("mid").value);
var fe = parseFloat(document.getElementById("fe").value);
var fp = parseFloat(document.getElementById("fp").value);
var sum=((a1+a2+a3+a4)/4)*(4*0.25)+(mid*0.25)+(fe*0.25)+(fp*0.25);
var grade;
if (sum >= 94.0) {
grade = "A";
} else if (sum <= 94.0 && sum >= 90.0) {
grade = "A-";
} else if (sum <= 90.0 && sum >= 87.0) {
grade = "B+";
} else if (sum <= 86.9 && sum >= 84.0) {
grade = "B";
} else if (sum <= 83.9 && sum >= 80.0) {
grade = "B-";
} else if (sum <= 79.9 && sum >= 77.0) {
grade = "C+";
} else if (sum <= 76.9 && sum >= 74.0) {
grade = "C";
} else if (sum <= 73.9 && sum >= 70.0) {
grade = "C-";
} else if (sum <= 69.9 && sum >= 67.0) {
grade = "D+";
} else if (sum <= 66.9 && sum >= 64.0) {
grade = "D";
} else if (sum <= 63.9 && sum >= 60.0) {
grade = "D-";
} else if (sum <= 60.0) {
grade = "F";
}
document.getElementById("result").innerHTML = ("The final percent grade is "+sum+"%. Your grade letter is: "+grade+".");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
a1: <input type="text" id="a1"><br><br>
a2: <input type="text" id="a2"><br><br>
a3: <input type="text" id="a3"><br><br>
a4: <input type="text" id="a4"><br><br>
mid: <input type="text" id="mid"><br><br>
finalexam: <input type="text" id="fe"><br><br>
finalproject: <input type="text" id="fp"><br><br>
<button onclick="myFunction()">Get Results</button><br><br>
<span id="result"></span>
</body>
</html>
Thank you.

Related

My code keeps returning undefined underneath the output

My JavaScript function keeps returning undefined underneath the correct output value.
let grade;
function getGrade(score) {
// Write your code here
if (score >= 25 && score <= 30) {
console.log('A');
}
else if (score >= 20 && score <= 25) {
console.log('B');
}
else if (score >= 15 && score <= 20) {
console.log('C');
}
else if (score >= 10 && score <= 15) {
console.log('D');
}
else if (score >= 5 && score <= 10) {
console.log('E');
}
else {
console.log('F');
}
return grade;
}
You haven't defined your grade. And it will always be undefined.
One way to do it is as follows:
function getGrade(score) {
var grade = "";
// Write your code here
if (score >= 25 && score <= 30) {
grade = "A";
}
else if (score >= 20 && score <= 25) {
grade = "B";
}
else if (score >= 15 && score <= 20) {
grade = "C";
}
else if (score >= 10 && score <= 15) {
grade = "D";
}
else if (score >= 5 && score <= 10) {
grade = "E";
}
else {
grade = "F";
}
return grade;
}
console.log(getGrade(27))
It seems you have return grade; at the bottom, but grade doesn't seem to be defined anywhere.
You should to set your variable "grade" value, or just delete
return grade;
Always check the console. It's currently singing at you, telling you grade is undefined.
You're trying to return something you haven't assigned a value to.
function getGrade(score) {
// ... //
return grade; //<-- nowhere do you define grade
}
Should be
function getGrade(score) {
let grade;
if (score >= 25 && score <= 30) grade = 'A';
else if (score >= 20 && score <= 25) grade = 'B';
else if (score >= 15 && score <= 20) grade = 'C';
else if (score >= 10 && score <= 15) grade = 'D';
else if (score >= 5 && score <= 10) grade = 'E';
else grade = 'F';
console.log(grade);
return grade;
}
Use return instead of console.log()
function getGrade(score) {
if (score >= 25 && score <= 30) {
return 'A'
}
else if (score >= 20 && score <= 25) {
return 'B'
}
else if (score >= 15 && score <= 20) {
return 'C';
}
else if (score >= 10 && score <= 15) {
return 'D';
}
else if (score >= 5 && score <= 10) {
return 'E';
}
else {
return 'F';
}
}
console.log(getGrade(20))
As there is difference of 5 b/w each grade range so you can use division and Math.floor
function getGrade(score) {
let grades = 'FEDCBA'
return score === 30 ? 'A' : grades[Math.floor((score)/5)]
}
console.log(getGrade(20))
console.log(getGrade(19))
console.log(getGrade(30))

HTML Form submitting parameters to function, and function not writing answer to innerHTML

A little exercise I'm working on that uses HTML5, CSS, and JavaScript. The objective has been detailed as:
*exercise on feb 26
- This is an exercise for the partial fulfillment of participation.
upload the answer on Moodle before 11:00 pm tomorrow
Late submission will not accepted, but partially completed answers will be awarded partial credit.
Question - rewrite the javascript script created in the previous exercises. Similar to the previous one, this new version still has two functions named functionA and functionB:
(1) functionA has one parameter and calculates the total score of a student taking CSC001. The course includes:
two quizzes - the full score of each quiz is 10 points, and the weight is 5%.
four assignments - the full score of each assignment is 100 points, and the weight is 5%.
a midterm exam - the full score is 50, and the weight is 10%.
a final exam - the full score is 100, and the weight is 40%.
a project - the full score is 25, and the weight is 25%.
The score of each coursework is stored as one element of an array. When it is called, this array is passed to the functionA via the functionA's parameter and then the functionA calculates the total score of a student.
After the total score is calculated, functionB is called that will calculate and then return the letter grade (represented by, such as A, B, C, D or F).
(2) when functionB is called, based on the total grade from step (1), function B calculates and returns the letter grade to functionA. The rules are listed below:
A 90% - 100%
B 80% - 82%
C 70% - 79%
D 60% - 69%
F 0% - 59%
(3) call functionA with an array represenring the score of each coursework
...
I wrote some code that is not reporting any error by the browser console, takes my numeric inputs into the fields, wipes them and seems to process, but writes nothing on the page in result. I was hoping someone more skilled in WebDev may give me some insight. Thank you!
<!DOCTYPE>
<html>
<head>
<title>Feb 26th</title>
</head>
<body bgcolor="gray">
<script type="text/javascript">
var totalScore;
function functionA(array) {
if (!(array.length == 9) || !(Array.isArray(array))){
return false;
}
if ((array[0] >= 0 && array[0] <= 10) && (array[1] >= 0 && array[1] <= 10)) {
var percentage1 = array[0] / 10;
var percentage2 = array[1] / 10;
var weightIndividual = 0.05 / 2;
array[0] = percentage1 * weightIndividual;
array[1] = percentage2 * weightIndividual;
}
else {
console.log('Quizes are out of bounds.');
}
if ((array[2] >= 0 && array[2] <= 100) && (array[3] >= 0 && array[3] <= 100) &&
(array[4] >= 0 && array[4] <= 100) && (array[5] >= 0 && array[5] <= 100)) {
var percentage1 = array[2] / 100;
var percentage2 = array[3] / 100;
var percentage2 = array[4] / 100;
var percentage2 = array[5] / 100;
var weightIndividual = 0.05 / 4;
array[2] = percentage1 * weightIndividual;
array[3] = percentage2 * weightIndividual;
array[4] = percentage1 * weightIndividual;
array[5] = percentage1 * weightIndividual;
}
else {
console.log('Assignments are out of bounds.');
}
if (array[6] >= 0 && array[6] <= 50) {
var percentage = array[6] / 50;
array[6] = percentage * .1;
}
else {
console.log('Midterm is out of bounds.');
}
if (array[7] >= 0 && array[7] <= 100) {
var percentage = array[7] / 100;
array[7] = percentage * .4;
}
else {
console.log('Final Exam is out of bounds.');
}
if (array[8] >= 0 && array[8] <= 25) {
var percentage = array[8] / 25;
array[8] = percentage * .25;
}
else {
console.log('Project is out bounds.');
}
for (i = 0; i < array.length; i++) {
totalScore += array[i];
}
functionB();
}
function functionB() {
try{
switch (totalScore) {
case (totalScore >= 90):
document.getElementById('result').innerHTML = 'A';
break;
case (totalScore < 90 && totalScore >= 80):
document.getElementById('result').innerHTML = 'B';
break;
case (totalScore < 80 && totalScore >= 70):
document.getElementById('result').innerHTML = 'C';
break;
case (totalScore < 70 && totalScore >= 60):
document.getElementById('result').innerHTML = 'D';
break;
case (totalScore < 60):
document.getElementById('result').innerHTML = 'F';
}
}
catch(e){
alert('Grades aren\'t all in yet.');
}
}
</script>
<style>
h1 {
text-align: center;
}
</style>
<h1>Grade Input</h1>
<form name="grades" id="grades" onsubmit="return functionA(array[quiz1, quiz2, assignment1, assignment2,
assignment3, assignment4, midterm, final, project])">
Enter grade for quiz 1:<br />
<input id="quiz1" name="quiz1" type="number"><br />
Enter grade for quiz 2:<br />
<input id="quiz2" name="quiz2" type="number"><br />
Enter grade for assignment1:<br />
<input id="assignment1" name="assignment1" type="number"><br />
Enter grade for assignment2:<br />
<input id="assignment2" name="assignment2" type="number"><br />
Enter grade for assignment3:<br />
<input id="assignment3" name="assignment3" type="number"><br />
Enter grade for assignment4:<br />
<input id="assignment4" name="assignment4" type="number"><br />
Enter grade for midterm exam:<br />
<input id="midterm" name="midterm" type="number"><br />
Enter grade for final exam:<br />
<input id="final" name="final" typ="number"><br />
Enter grade for project:<br />
<input id="project" name="project" type="number"><br />
<button type="submit" form="grades" value="submit">Submit</button>
</form>
<p id="result">
Your: grade is:
</p>
</body>
</html>
I found success with this code here:
<!DOCTYPE>
<html>
<head>
<title>Feb 26th</title>
</head>
<body bgcolor="gray">
<script type="text/javascript">
var totalScore = 0;
function functionA(array) {
if (!(array.length == 9) || !(Array.isArray(array))){
return false;
}
console.log(array);
if ((array[0] >= 0 && array[0] <= 10) && (array[1] >= 0 && array[1] <= 10)) {
var percentage1 = array[0] / 10;
var percentage2 = array[1] / 10;
var weightIndividual = 0.05 / 2;
array[0] = percentage1 * weightIndividual;
array[1] = percentage2 * weightIndividual;
}
else {
console.log('Quizes are out of bounds.');
}
if ((array[2] >= 0 && array[2] <= 100) && (array[3] >= 0 && array[3] <= 100) &&
(array[4] >= 0 && array[4] <= 100) && (array[5] >= 0 && array[5] <= 100)) {
var percentage1 = array[2] / 100;
var percentage2 = array[3] / 100;
var percentage2 = array[4] / 100;
var percentage2 = array[5] / 100;
var weightIndividual = 0.05 / 4;
array[2] = percentage1 * weightIndividual;
array[3] = percentage2 * weightIndividual;
array[4] = percentage1 * weightIndividual;
array[5] = percentage1 * weightIndividual;
}
else {
console.log('Assignments are out of bounds.');
}
if (array[6] >= 0 && array[6] <= 50) {
var percentage = array[6] / 50;
array[6] = percentage * .1;
}
else {
console.log('Midterm is out of bounds.');
}
if (array[7] >= 0 && array[7] <= 100) {
var percentage = array[7] / 100;
array[7] = percentage * .4;
}
else {
console.log('Final Exam is out of bounds.');
}
if (array[8] >= 0 && array[8] <= 25) {
var percentage = array[8] / 25;
array[8] = percentage * .25;
}
else {
console.log('Project is out bounds.');
}
for (i = 0; i < array.length; i++) {
console.log('Adding value of: ' + array[i]);
if (isNaN(array[i])) { array[i] = 0; };
totalScore += Number.parseInt(array[i] * 100);
}
event.preventDefault();
functionB();
}
function functionB() {
console.log('xxxxxxxxxxxxxx: ' + totalScore);
try {
if (totalScore >= 90) {
document.getElementById('result').innerHTML = 'A';
} else if (totalScore < 90 && totalScore >= 80) {
document.getElementById('result').innerHTML = 'B';
} else if (totalScore < 80 && totalScore >= 70) {
document.getElementById('result').innerHTML = 'C';
} else if (totalScore < 70 && totalScore >= 60) {
document.getElementById('result').innerHTML = 'D';
} else if (totalScore < 60) {
document.getElementById('result').innerHTML = 'F';
}
}
catch(e){
alert('Grades aren\'t all in yet.');
}
}
</script>
<style>
h1 {
text-align: center;
}
</style>
<h1>Grade Input</h1>
<form name="grades" id="grades" onsubmit="return functionA([document.getElementById('quiz1').value, document.getElementById('quiz2').value,
document.getElementById('assignment1').value, document.getElementById('assignment2').value, document.getElementById('assignment3').value,
document.getElementById('assignment4').value, document.getElementById('midterm').value, document.getElementById('final').value, document.getElementById('project').value])">
Enter grade for quiz 1:<br />
<input id="quiz1" name="quiz1" type="number"><br />
Enter grade for quiz 2:<br />
<input id="quiz2" name="quiz2" type="number"><br />
Enter grade for assignment1:<br />
<input id="assignment1" name="assignment1" type="number"><br />
Enter grade for assignment2:<br />
<input id="assignment2" name="assignment2" type="number"><br />
Enter grade for assignment3:<br />
<input id="assignment3" name="assignment3" type="number"><br />
Enter grade for assignment4:<br />
<input id="assignment4" name="assignment4" type="number"><br />
Enter grade for midterm exam:<br />
<input id="midterm" name="midterm" type="number"><br />
Enter grade for final exam:<br />
<input id="final" name="final" typ="number"><br />
Enter grade for project:<br />
<input id="project" name="project" type="number"><br />
<button type="submit" form="grades" value="submit">Submit</button>
</form>
<p id="result">
Your: grade is:
</p>
</body>
</html>

Using JS i need to create a Average variable

hi i need to create a Average variable that will average out my grades any help will be greatly appreciated i have the following. but i cant figure out the average portion of it
my code works for the inputs and gets the grades, and i also have the html portion
and i have an empty p tag for all of the inner html
function myFunction(){
let math = document.getElementById("math").value;
let science = document.getElementById("science").value;
let history = document.getElementById("history").value;
let english = document.getElementById("english").value;
let average = ( [ "math","science","history","english", ] );
// this is match sec
if(math >= 90) {
document.getElementById("mathG").innerHTML = "Your Grade is A"
}
else if (math >= 80 && math < 90) {
document.getElementById("mathG").innerHTML = "Your Grade is B"
}
else if (math >= 70 && math < 80) {
document.getElementById("mathG").innerHTML = "Your Grade is c"
}
else if (math >= 60 && math < 70) {
document.getElementById("mathG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("mathG").innerHTML = "Your Grade is F"
}
// Science section
if(science >= 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is A"
}
else if (science >= 80 && science < 90) {
document.getElementById("scienceG").innerHTML = "Your Grade is B"
}
else if (science >= 70 && science < 80) {
document.getElementById("scienceG").innerHTML = "Your Grade is c"
}
else if (science >= 60 && science < 70) {
document.getElementById("scienceG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("scienceG").innerHTML = "Your Grade is F"
}
// History
if(history >= 90) {
document.getElementById("historyG").innerHTML = "Your Grade is A"
}
else if (history >= 80 && history < 90) {
document.getElementById("historyG").innerHTML = "Your Grade is B"
}
else if (history >= 70 && history < 80) {
document.getElementById("historyG").innerHTML = "Your Grade is c"
}
else if (history >= 60 && history < 70) {
document.getElementById("historyG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("historyG").innerHTML = "Your Grade is F"
}
//English
english
if(english >= 90) {
document.getElementById("englishG").innerHTML = "Your Grade is A"
}
else if (english >= 80 && english < 90) {
document.getElementById("englishG").innerHTML = "Your Grade is B"
}
else if (english >= 70 && english < 80) {
document.getElementById("englishG").innerHTML = "Your Grade is c"
}
else if (english >= 60 && english < 70) {
document.getElementById("englishG").innerHTML = "Your Grade is d"
}
else {
document.getElementById("englishG").innerHTML = "Your Grade is F"
}
The code will be like this I guess :
let average = math + science + history + english / 4;
Here you will get the average and with the if else like you did for getting grades for each subject you can find the average grade as well.
if(average >= 90) {
average = "A";
}
Tip: You can use loop or map to reduce the line of code.
A few things:
First, make sure to cast your inputs to a number. It works with strings when doing a comparison with > or <, but if you try to add strings together with +, it will concatenate them rather then summing their numeric values.
Second, you can shorten your code by putting the duplicated if/else chains into a function.
Anyway, an average is just a sum divided by the number of summed items, so:
let average = (math + science + history + english) / 4;
would work. Or you can use a reduce if you have them in an array. This might come in handy if you frequently add or remove subjects:
let scores = [math, science, history, english];
let average = scores.reduce((total, score) => total + score) / scores.length;
Anyway, here's a snippet that seems to be working how you want:
function calculateAllGrades() {
let math = Number(document.getElementById("math").value);
let science = Number(document.getElementById("science").value);
let history = Number(document.getElementById("history").value);
let english = Number(document.getElementById("english").value);
// let average = ( [ "math","science","history","english", ] );
// Hardcoded, okay if these are all subjects:
let average = (math + science + history + english) / 4;
// Or if they change, you can use an array, easier if they change or you add more:
let scores = [math, science, history, english]
average = scores.reduce((sum, score) => sum + score) / scores.length
function calculateGrade(score, elementID) {
const element = document.getElementById(elementID);
if (score >= 90) {
element.innerHTML = "Your Grade is A";
} else if (score >= 80) {
element.innerHTML = "Your Grade is B";
} else if (score >= 70) {
element.innerHTML = "Your Grade is C";
} else if (score >= 60) {
element.innerHTML = "Your Grade is D";
} else {
element.innerHTML = "Your Grade is F";
}
}
calculateGrade(math, "mathG")
calculateGrade(science, "scienceG")
calculateGrade(history, "historyG")
calculateGrade(english, "englishG")
calculateGrade(average, "averageG")
}
let button = document.getElementById("button")
button.addEventListener("click", calculateAllGrades)
<div>MATH:<input type="text" id="math" /></div>
<div>SCIENCE:<input type="text" id="science" /></div>
<div>HISTORY:<input type="text" id="history" /></div>
<div>ENGLISH:<input type="text" id="english" /></div>
<br />
<div>MATH:<div id="mathG"></div></div><br/>
<div>SCIENCE:<div id="scienceG"></div></div><br/>
<div>HISTORY:<div id="historyG"></div></div><br/>
<div>ENGLISH:<div id="englishG"></div></div><br/>
<div>AVERAGE:<div id="averageG"></div></div><br/>
<button id="button">Calculate</button>
history is a global in browsers, so you can't use it as a variable name.
You should do something like:
let mathGrade = document.getElementById("math").value;
let scienceGrade = document.getElementById("science").value;
let historyGrade = document.getElementById("history").value;
let englishGrade = document.getElementById("english").value;
let average = (mathGrade + scienceGrade + historyGrade + englishGrade) / 4
Then, if you want the 'average' letter grade, you can do something similar to what you did for the other grades using the average:
if(average >= 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is A"
}
else if (average >= 80 && average < 90) {
document.getElementById("averageG").innerHTML = "Your Average Grade is B"
}
else if (average >= 70 && average < 80) {
document.getElementById("averageG").innerHTML = "Your Average Grade is c"
}
else if (average >= 60 && average < 70) {
document.getElementById("averageG").innerHTML = "Your Average Grade is d"
}
else {
document.getElementById("averageG").innerHTML = "Your Average Grade is F"
}

If statement does not repeat when condition is met?

I want the script to keep prompting the user for a valid input which is from 0 to 100 but can't get it to work. I am more confused than when I started to work on this script last night. This is my homework and the teacher has asked us to use if statement that is why I haven't tried to use the while loop but maybe I should.
Here is the code.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you score: ", "Your Score Here!"));
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>
Yes you would use a while loop. In this case you would have a flag that checks if the input is invalid. We can assume it's valid in the loop, and when the invalid check goes through change it to being invalid (false), and cause the loop to repeat.
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Grade</title>
<script type="text/javascript">
var grade = Number(prompt("What did you scrore: ", "Your Score Here!"));
var valid = false;
while(!valid)
{
valid = true; // assume it's valid
if (grade < 0 || grade > 100) {
grade = Number(prompt("Please enter a valid score", "Your Score Here!"));
valid = false; // It it happens to not be valid, change it to invalid
} else if (grade >= 0 && grade < 60) {
grade = "F";
} else if (grade >= 60 && grade < 70) {
grade = "D";
} else if (grade >= 70 && grade < 80) {
grade = "C";
} else if (grade >= 80 && grade < 90) {
grade = "B";
} else if (grade >= 90 && grade <= 100) {
grade = "A";
}
}
document.write("<strong>Your grade is:</strong> " + grade);
</script>
</head>
<body>
</body>
</html>

Javascript looping error with arrays

I am trying to prompt the user for a weight smaller than 126. Then my javascript is supposed to classify the weight into a category. I have used arrays but every time I loop it writes the 3rd array, superfly class. What can I do to make it function properly?
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
function recruit() {
var weightClass = wArray[0];
if (0 < weight && weight < 112) {
weightClass = wArray[1];
} else if (112 < weight && weight < 115) {
weightClass = wArray[2];
} else if (weight > 115 && weight < 118) {
weightClass = wArray[3];
} else if (weight > 118 && weight < 122) {
weightClass = wArray[4];
} else if (weight > 122 && weight < 126) {
weightClass = wArray[5];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}
Your first if condition is incorrect. You say if (112 < weight < 115). This first does 112 < weight, then takes the result of that and compares it to 115.
112 < weight evaluates to true or false; when used in numeric comparisons, true is 1 and false is 0. (Obviously) both 1 and 0 will always be less than 115, so this condition will always be true.
Also note that this script should be run onload of the page. This is because the div with the ID weight may not have loaded when the script executes and attempts to populate it. You can do this by saying:
<script type="text/javascript">
var wArray = ["fly", "superfly", "bantam", "superbantam", "feather"];
function calculateWeight() {
var weight = parseInt(prompt("What is your weight?"), 10);
while (weight > 126) {
alert('Please enter a weight lighter than 126');
weight = parseInt(prompt("What is your weight?"), 10);
}
recruit();
}
function recruit() {
var weightClass = wArray[0];
if (weight >= 112 && weight < 115) {
weightClass = wArray[1];
} else if (weight >= 115 && weight < 118) {
weightClass = wArray[2];
} else if (weight >= 118 && weight < 122) {
weightClass = wArray[3];
} else if (weight >= 122 && weight < 126) {
weightClass = wArray[4];
}
document.getElementById("weight").innerHTML = ('You are in ' + weightClass + ' class!');
}
</script>
<body onload="calculateWeight()">
<!-- include body contents here -->
</body>
the line:
if (112 < weight < 115) {
Should be
if (112 < weight && weight < 115) {

Categories

Resources