Recently I've started learning JavaScript in use with HTML. I wanted to create a simple calculator for a game I am using. You select a type of ore, the amount of the ore left in the asteroid, the value mined each cycle, and the duration of one cycle, and the script is supposed to return the volume of ore to be mined and number of cycles required as well as their total duration.
I've tried several things, like enclosing the function in try statement, but that didn't work either. I am asking for your help trying to figure out what I did wrong and point me in the right way. Thanks in advance.
<html>
<head>
<title>Mining Calculator - IndX: Industry Extension</title>
<script type="text/javascript">
function oreCalc() {
var ore = document.getElementById("ores").value;
var volume;
var amount = document.getElementById("amnt").value;
var yield = document.getElementById("yield").value;
var cycle = document.getElementById("cycle").value;
try{
switch(ore){
case "veldspar":
volume = 0.1;
break;
case "scordite":
volume = 0.15;
break;
case "pyroxeres":
volume = 0.3;
break;
case "plagioclase":
volume = 0.35;
break;
case "omber":
volume = 0.6;
break;
case "kernite":
volume = 1.2;
break;
case "jaspet":
volume = 2;
break;
case "hemorphite":
volume = 3;
break;
case "gneiss":
volume = 5;
break;
case "dark_ochre":
volume = 8;
break;
case "spodumain":
volume = 16;
break;
case "crokite":
volume = 16;
break;
case "arkonor":
volume = 16;
break;
case "mercoxit":
volume = 40;
break;
}
var rockvolume = amount * volume;
var cycles = rockvolume / yield;
var seconds = cycles * cycle;
var minutes;
while(seconds > 60)
{
seconds -= 60;
minutes++;
}
var text = "The asteroid has " + rockvolume + " m3 of ore. \n You'll mine it in " + Math.ceil(cycles) +
" cycles. \n It will take you " + minutes + "min " + Math.ceil(seconds) "s to mine.";
document.getElementById("output").innerHTML = text;
}
catch(err){
var text = "Input all required fields";
document.getElementById("output").innerHTML = text;
}
}
</script>
</head>
<body>
<table><tr><td>Ore:</td><td>
<select name="ores" id="ores" onchange="oreCalc()">
<option value="veldspar">Veldspar</option>
<option value="scordite">Scordite</option>
<option value="pyroxeres">Pyroxeres</option>
<option value="plagioclase">Plagioclase</option>
<option value="omber">Omber</option>
<option value="kernite">Kernite</option>
<option value="jaspet">Jaspet</option>
<option value="hemorphite">Hemorphite</option>
<option value="gneiss">Gneiss</option>
<option value="dark_ochre">Dark Ochre</option>
<option value="spodumain">Spodumain</option>
<option value="crokite">Crokite</option>
<option value="arkonor">Arkonor</option>
<option value="mercoxit">Mercoxit</option>
</select></td><td rowspan="4"><p id="output"></p></td></tr>
<tr><td>Amount:</td><td>
<input type="number" name="amount" id="amnt" oninput="oreCalc()">
</td></tr>
<tr><td>Yield:</td><td>
<input type="number" name="yield" id="yield" oninput="oreCalc()">
</td></tr>
<tr><td>Cycle duration:</td><td><input type="number" name="cycle" id="cycle" oninput="oreCalc()"></td></tr>
</table>
</body>
</html>
To track down these sorts of problems you need to use your browser's error console.
In Firefox it's Menu -> Developer -> Web Console
In Chrome it's Menu -> More Tools -> Javascript Console
In IE I think you hit F12 a click console.
I'm using Firefox and I see the following error on your page:
SyntaxError: missing ; before statement ore.html:66
And if you go to around line 66 you'll see:
var text = "The asteroid has " + rockvolume + " m3 of ore. \n You'll mine it in " + Math.ceil(cycles) +
" cycles. \n It will take you " + minutes + "min " + Math.ceil(seconds) "s to mine.";
Note the missing "+" after Math.ceil(seconds) but before "s to mine."? Add the plus sign and it should now work.
Btw, it's often better to use an external file for Javascript. I find it makes it much easier to manage and track down issues.
Related
My issue is I am not sure how to type the code to increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM in the do loop while having each text appended to the list. Each minute is supposed to be appended individually with text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);. An example is listed below. Any help would be appreciated.
What the function is supposed to do?
The function I have been attempting to create is supposed to allow the user to input three variables trainAMPH, trainBMPH and distanceApart. When the inputs are submitted, the function function calculateTrains() is supposed to calculate trainAMPH, trainBMPH into miles per minute trainAMPM and trainBMPM. There is a do-while loop in place to increment the minutesi , increment trainADistance by trainAMPM and decrease trainBDistance by trainBMPM. trainBDistance is supposed to contain the same value as distanceApart. The loop continues while(trainADistance < trainBDistance) and is supposed to append text into a list until the loop is broken. An example is listed below.
This is an example of what is supposed to be appended to to the list with inputs 70 for train A, 60 for train B and 260 for distance
• Minute 1 Train A Position: 1.17 miles Train B Position: 259.00 miles
• Minute 2 Train A Position: 2.33 miles Train B Position: 258.00 miles
• Minute 3 Train A Position: 3.50 miles Train B Position: 257.00 miles
• Minute 4 Train A Position: 4.67 miles Train B Position: 256.00 miles
• Minute 5 Train A Position: 5.83 miles Train B Position: 255.00 miles
My Code
<script>
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
let list = document.getElementById("list");
//calculates MPH into MPM(miles per minute)
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let text = "";
let i = 0;
let li = "";
// do that increments the minutes and Train A/Train B's current position
d do{
text += "Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2);
i++;
trainADistance += parseFloat(trainAMPM);
trainBDistance -= parseFloat(trainBMPM);
li = document.createElement("li");
}
// while loop tht continues while Train A distance is less than Train B distance
while(trainADistance < trainBDistance)
//adds "text" variable listed in do while loop to list
li.innerHTML = text;
list.appendChild(li);
// documents the amount of minutes to the "results" div
document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes.";
}
</script>
<body>
<form id="myForm">
<label>Train A's Speed</label>
<input id="trainAMPH" type="number" value="" placeholder="MPH">
<label>Train B's Speed</label>
<input id="trainBMPH" type="number" value="" placeholder="MPH" >
<label>Distance between Eastford and Westford</label>
<input id="distanceApart" type="number" value=""placeholder="Miles">
<input type ="button" value="Submit Values" onclick="calculateTrains()">
<ul id = "list"></ul>
<div id="results"></div>
</form>
</body>
There were some issue with the code, I have made the necessary changes. Please go through the in-line comments that I have added in order to understand what were the mistakes and how they can be fixed.
The code is working now, please use the below snippet to run and see it's output. Do make sure to see my comments. Goodluck!
function calculateTrains() {
let trainAMPH = +document.getElementById("trainAMPH").value;
let trainBMPH = +document.getElementById("trainBMPH").value;
let distanceApart, trainBDistance;
//The input you retrieve using .value will be a string, convert it to Number using + to use toFixed
distanceApart = trainBDistance = +document.getElementById("distanceApart")
.value;
let list = document.getElementById("list");
//calculates MPH into MPM(miles per minute)
trainAMPM = trainAMPH / 60;
trainBMPM = trainBMPH / 60;
let trainADistance = 0;
let i = 1;
let text = "";
// do that increments the minutes and Train A/Train B's current position
do {
//don't use text+=, you don't want to append, you want each <li> to be on a separate line
text =
"Minute " +
i +
" Train A Position: " +
trainADistance.toFixed(2) +
" miles" +
"Train B Position: " +
trainBDistance.toFixed(2);
//create list item using template literals
let li = `<li>${text}</li>`;
//use insertAdjaventHTML( ) function to append the above created literal to list <ul>
list.insertAdjacentHTML("beforeend", li);
//increment i
i++;
//do the train A and train B distance calculations
//without these calculations, your while exit condition from below will never be met,
//making it an infinite while loop
trainADistance += trainAMPM;
trainBDistance -= trainBMPM;
} while (
// while loop tht continues while Train A distance is less than Train B distance
trainADistance < trainBDistance
);
//don't use innerHTML to append text, innerHTML is to append HTML string like '<div> hello <div>'
//instead use textContent or innerText properties
document.getElementById("results").textContent =
"The two trains met after " + i + "minutes.";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<body>
<form id="myForm">
<label>Train A's Speed</label>
<input id="trainAMPH" type="number" value="" placeholder="MPH" />
<label>Train B's Speed</label>
<input id="trainBMPH" type="number" value="" placeholder="MPH" />
<label>Distance between Eastford and Westford</label>
<input id="distanceApart" type="number" value="" placeholder="Miles" />
<input
type="button"
value="Submit Values"
onclick="calculateTrains()"
/>
<ul id="list"></ul>
<div id="results"></div>
</form>
</body>
<script src="script.js"></script>
</body>
</html>
the reason why trainBDistance.toFixed(2) isn't recognized as a function is because when call document.getElementById("distanceApart").value the data type is string u need to parseInt or parseFloat that value first. You condition is while(trainADistance < trainBDistance) so you need to increment trainADistance as you said.
This might help.
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = parseInt( document.getElementById("distanceApart").value );
let list = document.getElementById("list");
list.innerHTML = ''; //empty the list
//calculates MPH into MPM(miles per minute)
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let i = 0;
// do that increments the minutes and Train A/Train B's current position
do{
let text = "Minute " + i + " Train A Position: "+ trainADistance.toFixed(2) + " miles" + " Train B Position: " + trainBDistance.toFixed(2);
//adds "text" variable listed in do while loop to list
let li = document.createElement("li");
li.innerHTML = text;
list.appendChild(li);
i++;
trainADistance += trainAMPM; //increment trainADistance by trainAMPM
trainBDistance -= trainBMPM; //decrease trainBDistance by trainBMPM
}while(trainADistance < trainBDistance)
// while loop tht continues while Train A distance is less than Train B distance
// documents the amount of minutes to the "results" div
document.getElementById("results").innerHTML = "The two trains met after " + i + "minutes.";
}
You may wanna change you script to as follows:
<script>
function calculateTrains(){
let trainAMPH= document.getElementById("trainAMPH").value;
let trainBMPH= document.getElementById("trainBMPH").value;
let distanceApart = trainBDistance = document.getElementById("distanceApart").value;
let list = document.getElementById("list");
trainAMPM = (trainAMPH / 60);
trainBMPM = (trainBMPH / 60);
let trainADistance = 0;
let text = "";
let i = 0;
do{
i++;
trainADistance+=trainAMPM
trainBDistance-=trainBMPM
let li = document.createElement('li')
li.textContent="Minute " + i + " Train A Position: "+ parseFloat(trainADistance).toFixed(2) + " miles" + "Train B Position: " + parseFloat(trainBDistance).toFixed(2)
document.getElementById('list').appendChild(li)
}while(trainADistance<=trainBDistance)
}
</script>
I have made this function here to calculate prices from choices in the select menu. I have made a switch but I dont understand where to input my function to trigger it (on html). The 2 other functions changeit() and changerepas() are onchange functions that will give you the basic price. (they are not linked to the question) (Note: This is my first switch ever, so it might look noobish to most of you. )
function taxesrepas(option){
var soustot;
var taxes;
var taxer;
var taxetotal = taxes + taxer;
var total = taxetotal + soustot;
var pricee;
var pricer;
var soustot = pricee + pricer;
switch (option){
case "spaghetti":
taxer = 0.69;
pricer = 8.95
break;
case "lasagne":
taxer = 0.75;
pricer = 9.95;
break;
case "salade":
taxes = 0.45;
pricee = 5.95;
break;
case "escargot":
taxes = 0.38;
pricee = 4.95;
break;
}
document.getElementById("taxes").innerHTML = taxetotal;
document.getElementbyid("total").innerHTML = total;
document.getElementbyid("soustot").innerHTML = soustot;
}
<select name="entree" id="entree" onChange="changeit(this.value)">
<option value="hidden" selected>Choisir...</option>
<option value="salade">Salade</option>
<option value="escargot">Escargot</option>
</select>
<img display="inline" id="imgselect" src="" alt="0.00$"/>
<h3 id= "choix1"></h3>
<p>Repas</p>
<select name="repas" id="repas" onChange="changerepas(this.value)">
<option value="hidden1" selected>Choisir...</option>
<option value="spaghetti">Spaghetti</option>
<option value="lasagne">Lasagne</option>
</select>
<h3 id="choix"></h3>
<h3 id="taxes"></h3>
<h3 id="soustotal"></h3>
<h3 id="total"></h3>
Maybe change the onChange to
function(){
taxesrepas(this.value);
changeit(this.value);
}
I've just begun learning javascript, and I'm running into an issue where only one of my 3 currently coded buttons will either recognize a click, or run the function associated when I click it. This first example of code works wonderfully;
The HTML
<div id="commonchecks">
<h3>Common Checks:</h3>
<p>Type of Check:</p>
<select id="CheckType">
<option value="Strength">Strength</option>
<option value="Stamina">Stamina</option>
<option value="Agility">Agility</option>
<option value="Intelligence">Intelligence</option>
<option value="Charisma">Charisma</option>
<option value="Perception">Perception</option>
</select>
<p>Complexity:</p>
<select id="Complexity">
<option value="Simple">Simple</option>
<option value="Complex">Complex</option>
</select>
<p>Circumstantial Factors (+/-):</p>
<input type="number" id="bxCircumstantialFactors" value="-2">
<h3 class="details">Check Details:</h3>
<p id="success" class="details">It was a XXXXXXX!</p>
<p id="rolltotal" class="details">You rolled a(n) XX.</p>
<p id="rollstandards" class="details">You needed a(n) XX or higher.</p>
<p id="experience" class="details">Experience Payout: 00 exp!</p>
<p id="duplicate">DUPLICATE!</p>
<button onclick="CheckRoll()" class="button" id="RollCheckButton">Roll</button>
</div>
And the javascript
function CheckRoll() {
//Loading Variables Up From User Input
numStrength = Number(document.getElementById("bxStrength").value);
numStamina = Number(document.getElementById("bxStamina").value);
numAgility = Number(document.getElementById("bxAgility").value);
numIntelligence = Number(document.getElementById("bxIntelligence").value);
numCharisma = Number(document.getElementById("bxCharisma").value);
numPerception = Number(document.getElementById("bxPerception").value);
numCircumstantialFactors = Number(document.getElementById("bxCircumstantialFactors").value);
//Making the Roll
numRoll = Math.floor(Math.random() * 20 + 1);
if (document.getElementById("duplicate").style.visibility === "visible"){
document.getElementById("duplicate").style.visibility = "hidden";
}
//Checking to see if the roll was a duplicate
if (numRoll === prevRoll) {
document.getElementById("duplicate").style.visibility = "visible";
}
//Checking the complexity of the check
switch (document.getElementById("Complexity").value){
case "Simple":
numBaseAddition = 10;
numStatModifier = 2;
break;
case "Complex":
numBaseAddition = 0;
numStatModifier = 1;
break;
}
//Checking the stat associated and marking it as the calculated stat
switch (document.getElementById("CheckType").value) {
case "Strength":
numRelevantStatValue = numStrength;
break;
case "Stamina":
numRelevantStatValue = numStamina;
break;
case "Agility":
numRelevantStatValue = numAgility;
break;
case "Intelligence":
numRelevantStatValue = numIntelligence;
break;
case "Charisma":
numRelevantStatValue = numCharisma;
break;
case "Perception":
numRelevantStatValue = numPerception;
break;
}
//Determining how much value of a stat effects your chances of success
numStatAddition = numRelevantStatValue / numStatModifier;
//Determining your factor of success
numSuccessFactor = numBaseAddition + numStatAddition + numCircumstantialFactors;
//If success factor is a 20 or higher, set it to 19 since one can always roll a 1
if (numSuccessFactor >= 20){
numSuccessFactor = 19;
}
//Calculating the number you need to beat
numFailureFactor = 20 - numSuccessFactor;
//If failure factor is a 20 or higher, set it to 19 since one can always roll a 20
if (numFailureFactor >= 20) {
numFailureFactor = 19;
}
//Calculating amount of experience possible to be earned
numExperience = numFailureFactor * 5;
//Reporting on the successfulness or not
if (numRoll >= numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a SUCCESS!";
}
if (numRoll === 20){
document.getElementById("success").innerHTML = "It was a CRITICAL SUCCESS!";
}
if (numRoll < numFailureFactor + 1){
document.getElementById("success").innerHTML = "It was a FAILURE!";
numExperience = 0;
}
if (numRoll === 1){
document.getElementById("success").innerHTML = "It was a CRITICAL FAILURE!";
numExperience = 0;
}
//Reporting the dice roll
document.getElementById("rolltotal").innerHTML = "You rolled a(n) " + numRoll + ".";
//Reporting the standards
document.getElementById("rollstandards").innerHTML = "You needed a(n) " + (numFailureFactor + 1) + " or higher.";
//Reporting experience gain
document.getElementById("experience").innerHTML = "Experience Payout: " + numExperience + " exp!";
//Saving last roll
prevRoll = numRoll;
However, on a much simpler function, it won't work for whatever reason. I've tried putting the javascript into firefox's debugger, and it didn't reveal any syntax mistakes. Here's the section that won't work.
The HTML
<p class="blocksection">Block Type:</p>
<select id="blocktype">
<option value="Unarmed">Unarmed</option>
<option value="Armed">Armed</option>
</select>
<p class="blocksection" id="blockreporter">Your Block total is a(n) XX!</p>
<p class="blocksection" id="blockduplicate">DUPLICATE!</p>
<button onclick="BlockRoll()" class="button" id="blockbutton">Block!</button>
And the javascript
function BlockRoll() {
numStamina = Number(document.getElementById("bxStamina").value);
if (document.getElementById("blocktype").value === "Unarmed") {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + Math.floor(Math.random() * 6 + 1) + "!";
}
else {
document.getElementById("blockreporter").InnerHTML = "Your Block total is a(n) " + (Math.floor(Math.random() * 6 + 1) + (numStamina/2)) + "!";
}
}
I'm not used to this language, but I know c# well enough and they appear relatively similar. Is there a really simple mistake that I'm making somewhere?
Thanks
You're calling element.InnerHTML in your second example which is incorrect, as the correct value is innerHTML (note the lowercase i.)
If you hit F12 (in most browsers) the developer console will come up and show you common errors like these.
I'm having an issue with getting the value of a select option and calculating it, the issue is that everytime i select an option a random '0' keeps being displayed before it. Any help would be appreciated, here is the relevant code:
<div class="otherCars">
<label for="otherCars">Do you drive any other cars?</label>
<select name="otherCars" class="style1" id="carsSelect" onchange="getQuote()" onblur="validateSelect('cars')" >
<option value="empty">-Please select-</option>
<option value="10" id="car1">No access to any other cars </option>
<option value="20">Own another car</option>
<option value="100">Named driver on another policy</option>
<option value="100">Company car (including personal use)</option>
<option value="100">Company car (excluding personal use)</option>
</select>
</div><!-- Closing div tag-->
Javascript:
function getQuote(){
var disqualifiedDifference = 0;
var genderDifference = 0;
var carDifference = 0;
var menuSelect = document.getElementById("carsSelect");
var carValue = menuSelect.options[menuSelect.selectedIndex].value;
function genderPrice(){
if (document.getElementById("male").checked){
genderDifference += 200;
}
if (document.getElementById("female").checked){
genderDifference += 175;
}
}
function disqoPrice(){
if (document.getElementById("yes").checked){
disqualifiedDifference += 300;
}
if (document.getElementById("no").checked){
disqualifiedDifference += 0;
}
}
function carPrice(){
if (document.getElementById("car1").selected){
carDifference += 200;
}
if (document.getElementById("car2").selected){
carDifference += 20;
}
}
genderPrice();
disqoPrice();
var totalPrice = disqualifiedDifference + genderDifference + carDifference + carValue;
document.getElementById('totalPrice').innerHTML = totalPrice;
} //end of CalculateTotal
menuSelect.options[menuSelect.selectedIndex].value returns a string, which means that the + operator will be performing string concatenation rather than addition. Cast the value to a Number before trying to do arithmetic.
var carValue = +menuSelect.options[menuSelect.selectedIndex].value;
// ^ unary + operator casts a string to a number
Could anyone help me figure out a better way of returning the right message based on my if...else logic? So I'm trying to calculate a student's GPA via dropdown menus. Each letter is your standard fare (A = 4.0, B = 3.5, etc). Now, if a student has a calculated GPA that is >= 3.5, I want to display a certain message. If It's anything lower, I'd display another message. I'm having a hard time figuring out how to print the message based on the condition.
function letterToGrade(gpa){
var grade;
switch (gpa)
{
case "A": grade = 4.0;
break;
case "B": grade = 3.0;
break;
case "C": grade = 2.0;
break;
case "D": grade = 1.0;
break;
case "F": grade = 0.0;
break;
}
return grade;
}
function calculateGPA(){
var numOfRequisites = 5;
var gpa1 = letterToGrade(document.getElementById("Foundation").value);
var gpa2 = letterToGrade(document.getElementById("Database").value);
var gpa3 = letterToGrade(document.getElementById("Elect").value);
var gpa4 = letterToGrade(document.getElementById("Commerce").value);
var gpa5 = letterToGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
var result = "<p>Your calculated GPA is: "+(gpaTotal.toFixed(1))+"<br></p>";
if (gpaTotal >= 3.5)
return result += "<p>Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program.</p>";
else
return result += "<p>Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time.</p>";
document.getElementById("result").innerHTML=result;
}
And here's the HTML. Not all of it.
<h4>Thank you for your interest in our summer internship program. Please enter your GPA for the following courses. </h4>
<p>
IT 3503 Foundation of HIT:
<select id="Foundation">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4153 Advanced Database:
<select id="Database">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4513 Elect Health Rec Sys & Ap:
<select id="Elect">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4123 Electronic Commerce:
<select id="Commerce">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
IT 4533 Health Info Sec & Priv:
<select id="HealthInfo">
<option> </option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<br/>
</form>
<input type="button" value="Submit" onclick="calculateGPA()" />
</p>
The last part kind of messes me up. I'm pretty new to HTML and Javascript. This is for a school assignment, so please feel free to insult me as you will for being a slacker.
you have several problems
grade is never defined
you return before the other code can be executed
numGrade is undefined. probably mean for CalculateGPA to be numGrade, or vise versa
So
function CalculateGPA(){
//grade here is undefined as it isnt declared before here
switch (grade) {
case "A":
grade = 4.0;
break;
case "B":
grade = 3.0;
break;
case "C":
grade = 2.0;
break;
case "D":
grade = 1.0;
break;
case "F":
grade = 0.0;
break;
}
return grade; //you return here so any code after this is never executed
var numOfRequisites = 5;
var gpa1 = numGrade(document.getElementById("Foundation").value);
var gpa2 = numGrade(document.getElementById("Database").value);
var gpa3 = numGrade(document.getElementById("Elect").value);
var gpa4 = numGrade(document.getElementById("Commerce").value);
var gpa5 = numGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
if (gpaTotal >= 3.5)
return acceptanceMessage;
else
return consolationMessage;
//document.getElementById("result").innerHTML=message;
}
i think you want:
function numGrade(gpa){
switch (gpa) {
case "A": gpa = 4.0;
break;
case "B": gpa = 3.0;
break;
case "C": gpa = 2.0;
break;
case "D": gpa = 1.0;
break;
case "F": gpa = 0.0;
break;
}
return gpa;
}
function calculateGradeAndGenMessage(){
var numOfRequisites = 5;
var gpa1 = numGrade(document.getElementById("Foundation").value);
var gpa2 = numGrade(document.getElementById("Database").value);
var gpa3 = numGrade(document.getElementById("Elect").value);
var gpa4 = numGrade(document.getElementById("Commerce").value);
var gpa5 = numGrade(document.getElementById("HealthInfo").value);
var gpaTotal = (gpa1 + gpa2 + gpa3 + gpa4 + gpa5)/numOfRequisites ;
if (gpaTotal >= 3.5)
return acceptanceMessage;
else
return consolationMessage;
}
document.getElementById("result").innerHTML=calculateGradeAndGenMessage();
As stated in the comments, you never defined gpa. However, I noticed you wanted to clean up your code a bit...I recommend going about this by breaking it up into two functions:
DEMO:
http://jsfiddle.net/dirtyd77/Q86gt/4/
JAVASCRIPT:
//Calculate average GPA of 5 classes.
//If avereage GPA >= 3.5, show acceptance message.
//Else thank for applying.
var consolationMessage = "<p>Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time.";
var acceptanceMessage = "Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program."
//get the gpa
function getGPA() {
var gpaTotal = null,
message = null,
classes = ['Foundation', 'Database', 'Elect', 'Commerce', 'HealthInfo'];
//iterate over classes
for (var i = 0; i < classes.length; i++) {
var gpa = calculateGPA(document.getElementById(classes[i]).value);
gpaTotal += gpa;
}
//gpaTotal divided by number of classes
gpaTotal /= classes.length;
//if not all values are filled out, alert and return
if (isNaN(gpaTotal)) {
alert('Please fill out all answers!');
return;
}
if (gpaTotal >= 3.5) message = acceptanceMessage;
else message = consolationMessage;
document.getElementById("result").innerHTML = message;
}
function calculateGPA(gpa) {
switch (gpa) {
case "A":
gpa = 4.0;
break;
case "B":
gpa = 3.0;
break;
case "C":
gpa = 2.0;
break;
case "D":
gpa = 1.0;
break;
case "F":
gpa = 0.0;
break;
}
return gpa;
}
HTML:
<h4>Thank you for your interest in our summer internship program. Please enter your GPA for the following courses. </h4>
<p>IT 3503 Foundation of HIT:</p>
<select id="Foundation">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4153 Advanced Database:</p>
<select id="Database">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4513 Elect Health Rec Sys & Ap:</p>
<select id="Elect">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4123 Electronic Commerce:</p>
<select id="Commerce">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<p>IT 4533 Health Info Sec & Priv:</p>
<select id="HealthInfo">
<option></option>
<option>A</option>
<option>B</option>
<option>C</option>
<option>D</option>
<option>F</option>
</select>
<input type="button" value="Submit" onclick="getGPA()" />
<p id="result"></p>
Hope this helps and let me know if you have any questions.
I missed this return statement originally but you return gpa after your switch statement.
This will cause your function to end as it has been returned already.
Then after return gpa you have two other unnecessary return statements in your if block.
You should break up the calculation of the GPA and the message generation separately.
function calculateGPA(letterGrade) {
var gpa;
switch (letterGrade) {
case 'A':
gpa = 4.0;
break;
case 'B':
gpa = 3.0;
break;
case 'C':
gpa = 2.0;
break;
case 'D':
gpa = 1.0;
break;
case 'F':
gpa = 0.0;
break;
}
return gpa;
}
function averageGPA() {
var gpas = [],
sum = 0,
numberGPA;
gpas.push(calculateGPA(document.getElementById("Foundation").value));
gpas.push(calculateGPA(document.getElementById("Database").value));
gpas.push(calculateGPA(document.getElementById("Elect").value));
gpas.push(calculateGPA(document.getElementById("Commerce").value));
gpas.push(calculateGPA(document.getElementById("HealthInfo").value));
for (var i = gpas.length - 1; i >= 0; i--) {
sum += gpas[i]
};
return sum / gpas.length;
}
function passMessage(gpa) {
var result = document.getElementById('result'),
message;
if (gpa >= 3.5) {
message = "Congratulations! Based on your GPA, we will move forward with your application " +
"for this prestigious internship program.";
} else if (gpa < 3.5) {
message = "Thank you for your interest in this program. Unfortunately at this time, " +
"we are unable to continue with your application due to our strict GPA standards. Please try again " +
"at a later time";
}
result.innerHTML = message;
}
function checkGPAResults() {
passMessage(averageGPA());
}
And a fiddle