0

<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
 var grade = new Array(9); 
 var credit = new Array(9);
 var getGrade = new Array(5);
 var getCredit = new Array(5);
 var gradeCount = 12; 
 grade[0] = "A+";
 credit[0] = 4;
 grade[1] = "A"; 
 credit[1] = 4; 
 grade[2] = "A-";
 credit[2] = 3.7;
 grade[3] = "B+";
 credit[3] = 3.3;
 grade[4] = "B";
 credit[4] = 3;
 grade[5] = "B-";
 credit[5] = 2.7;
 grade[6] = "C+";
 credit[6] = 2;
 grade[7] = "C-";
 credit[7] = 1.7;
 grade[8] = "D+";
 credit[8] = 1.3;
 grade[9] = "D";
 credit[9] = 1;
 grade[10] = "D-";
 credit[10] = 0.7;
 grade[11] = "F";
 credit[11] = 0.0;
 getGrade[0] = document.calcGpaForm.grade1.value;
 getGrade[0] = getGrade[0].toUpperCase();
 getGrade[1] = document.calcGpaForm.grade2.value;
 getGrade[1] = getGrade[1].toUpperCase();
 getGrade[2] = document.calcGpaForm.grade3.value;
 getGrade[2] = getGrade[2].toUpperCase();
 getGrade[3] = document.calcGpaForm.grade4.value;
 getGrade[3] = getGrade[3].toUpperCase();
 getGrade[4] = document.calcGpaForm.grade5.value;
 getGrade[4] = getGrade[4].toUpperCase();
 getGrade[5] = document.calcGpaForm.grade6.value;
 getGrade[5] = getGrade[5].toUpperCase();
 getCredit[0] = document.calcGpaForm.credit1.value;
 getCredit[1] = document.calcGpaForm.credit2.value;
 getCredit[2] = document.calcGpaForm.credit3.value;
 getCredit[3] = document.calcGpaForm.credit4.value;
 getCredit[4] = document.calcGpaForm.credit5.value;
 getCredit[5] = document.calcGpaForm.credit6.value;
 
 var totalGrades =0;
 var totalCredits = 0;
 var GPA = 0;
 var i = 0;
 

 for (i; i < 6; i++) {
        if (getGrade[i] == "") {
   break;
  }
  else if (getGrade[i] == "c" || getGrade[i] == "C") {
   alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
   return;
  }
  else if (isNaN(getCredit[i])) {
   alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
   return;
  }
  else if (getCredit[i] == "") {
   alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
   return;
  }
        var validgradecheck = 0;
  var x = 0;
        for (x; x < gradeCount; x++) {
            if (getGrade[i] == grade[x]) {
    totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
                totalCredits = totalCredits + parseInt(getCredit[i],10);
                validgradecheck = 1;
                break;
            }
        }
        if (validgradecheck == 0) {
            alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
             return;
        }
    }
 if (totalCredits == 0) {
        alert("Total credits cannot equal zero.");
        return;
    }
 GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
 alert("GPA =  " + eval(GPA));
 return;
 
}

function copyRight() {
 var lastModDate = document.lastModified;
 var lastModDate = lastModDate.substring(0,10);
 displayDateLast.innerHTML = "<h6>Copyright &copy; Haiwook Choi. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}

//-->
</script>
<style type="text/css">
<!--
.align-center {
 text-align:center;
}

table {
 margin-left: auto;
 margin-right: auto;
 width: 70%;
}

.block {
 width: 50%;
 margin-right: auto;
 margin-left: auto;
}

.center-div {
 width: 70%;
 margin-right: auto;
 margin-left: auto;
}

.header-text {
 font-family: Arial, Helvetica, sans-serif;
 font-size: 12pt;
 font-weight: bold;
 text-align: center;
}

.center-items {
 text-align: center;
}

.right-align {
 text-align: right;
 width: 50%;
}

.left-align {
 text-align: left;
 width: 50%;
}

#displayDateLast {
 text-align: left;
 width: 50%;
 margin-right: auto;
 margin-left: auto;
}

-->
</style>

I'm trying to make a webpage that allows the user to enter from 4 to 6 grades for any course. Next to the letter grade, I'm wanting to put a text-field that accepts the credit hours for the courses. Also when the Calculate GPA button is clicked I want it to verify that a letter grade has been entered and then accumulate the grade points as well as the credit hours and display the GPA. I'm having trouble getting the GPA to calculate though. As well as having an alert display when a user enters anything other than a letter grade? Can someone look over my code and tell me what I should fix or add? Thanks if you read this and attempt to help!

<!DOCTYPE HTML>  
<html>
<head>
<meta charset="utf-8"> 
<title>Chapter 10 Cases and Places: 2</title>
<script type="text/javascript">
<!--Hide from old browsers
function gpacalc() {
 var grade = new Array(9); 
 var credit = new Array(9);
 var getGrade = new Array(5);
 var getCredit = new Array(5);
 var gradeCount = 12; 
 grade[0] = "A+";
 credit[0] = 4;
 grade[1] = "A"; 
 credit[1] = 4; 
 grade[2] = "A-";
 credit[2] = 3.7;
 grade[3] = "B+";
 credit[3] = 3.3;
 grade[4] = "B";
 credit[4] = 3;
 grade[5] = "B-";
 credit[5] = 2.7;
 grade[6] = "C+";
 credit[6] = 2;
 grade[7] = "C-";
 credit[7] = 1.7;
 grade[8] = "D+";
 credit[8] = 1.3;
 grade[9] = "D";
 credit[9] = 1;
 grade[10] = "D-";
 credit[10] = 0.7;
 grade[11] = "F";
 credit[11] = 0.0;
 getGrade[0] = document.calcGpaForm.grade1.value;
 getGrade[0] = getGrade[0].toUpperCase();
 getGrade[1] = document.calcGpaForm.grade2.value;
 getGrade[1] = getGrade[1].toUpperCase();
 getGrade[2] = document.calcGpaForm.grade3.value;
 getGrade[2] = getGrade[2].toUpperCase();
 getGrade[3] = document.calcGpaForm.grade4.value;
 getGrade[3] = getGrade[3].toUpperCase();
 getGrade[4] = document.calcGpaForm.grade5.value;
 getGrade[4] = getGrade[4].toUpperCase();
 getGrade[5] = document.calcGpaForm.grade6.value;
 getGrade[5] = getGrade[5].toUpperCase();
 getCredit[0] = document.calcGpaForm.credit1.value;
 getCredit[1] = document.calcGpaForm.credit2.value;
 getCredit[2] = document.calcGpaForm.credit3.value;
 getCredit[3] = document.calcGpaForm.credit4.value;
 getCredit[4] = document.calcGpaForm.credit5.value;
 getCredit[5] = document.calcGpaForm.credit6.value;
 
 var totalGrades =0;
 var totalCredits = 0;
 var GPA = 0;
 var i = 0;
 

 for (i; i < 6; i++) {
        if (getGrade[i] == "") {
   break;
  }
  else if (getGrade[i] == "c" || getGrade[i] == "C") {
   alert("'C' is not a vaild letter grade. Course " +eval(i + 1)+ ".")
   return;
  }
  else if (isNaN(getCredit[i])) {
   alert("Enter a vaild number of credits for Course " +eval(i + 1)+ ".")
   return;
  }
  else if (getCredit[i] == "") {
   alert ("You left the number of credits blank for Course " +eval(i + 1)+ ".")
   return;
  }
        var validgradecheck = 0;
  var x = 0;
        for (x; x < gradeCount; x++) {
            if (getGrade[i] == grade[x]) {
    totalGrades = totalGrades + (parseInt(getCredit[i],10) * credit[x]);
                totalCredits = totalCredits + parseInt(getCredit[i],10);
                validgradecheck = 1;
                break;
            }
        }
        if (validgradecheck == 0) {
            alert("Could not recognize the grade entered for Course " +eval(i + 1)+ ".");
             return;
        }
    }
 if (totalCredits == 0) {
        alert("Total credits cannot equal zero.");
        return;
    }
 GPA = Math.round(( totalGrades / totalCredits ) * 100) / 100;
 alert("GPA =  " + eval(GPA));
 return;
 
}

function copyRight() {
 var lastModDate = document.lastModified;
 var lastModDate = lastModDate.substring(0,10);
 displayDateLast.innerHTML = "<h6>Copyright &copy; Hannah. "+" <br /> This document was last modified "+lastModDate+".</h6>";
}

//-->
</script>
<style type="text/css">
<!--
.align-center {
 text-align:center;
}

table {
 margin-left: auto;
 margin-right: auto;
 width: 70%;
}

.block {
 width: 50%;
 margin-right: auto;
 margin-left: auto;
}

.center-div {
 width: 70%;
 margin-right: auto;
 margin-left: auto;
}

.header-text {
 font-family: Arial, Helvetica, sans-serif;
 font-size: 12pt;
 font-weight: bold;
 text-align: center;
}

.center-items {
 text-align: center;
}

.right-align {
 text-align: right;
 width: 50%;
}

.left-align {
 text-align: left;
 width: 50%;
}

#displayDateLast {
 text-align: left;
 width: 50%;
 margin-right: auto;
 margin-left: auto;
}

-->
</style>
</head>
<body onLoad="gpacalc(); copyRight()">
<div class="center-div">
 <p style="font-family:Arial, Helvetica, sans-serif; font-size:xx-large; font-weight:bold; text-align: center; color:blue">Calculating Your GPA</p>
<p class="block"><strong>Directions: </strong>Enter your letter grade for your courses. In the boxes to the right enter the credit hours per course. Then Click the Calculate GPA button to have your GPA calculated as well as your total credit hours.</p>
<form name="calcGpaForm" method="post">

  <table>
  <tr>
  <h4 style="text-align: center">Letter Grade:</h4>
  
           <th class="right-align">
              <span style="color:#cc0000;"></span>Course 1:
           </th>
           <td class="align-left"><input type="text" name="grade1" type="text" id="grade1"  size="10" onBlur="validgradecheck" /></td>
     <td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10" /></td>
        </tr>
        <tr>
          <th class="right-align">
             <span style="color:#cc0000;"></span>Course 2:
          </th>
          <td class="align-left"><input name="grade2" type="text" id="grade2" size="10" onBlur="validgradecheck" /></td>
    <td class="align-left"><input type="text" name="credit2" id="credit2" size="10" /></td>
        </tr>
        <tr>
          <th class="right-align">
             <span style="color:#cc0000;"></span>Course 3:
          </th>
             <td class="align-left"><input name="grade3" type="text" id="grade3" size="10" onBlur="validgradecheck" /></td>  
    <td class="align-left"><input type="text" name="credit3" id="credit3" size="10" /></td>
        </tr>
        <tr>
           <th class="right-align">
              <span style="color:#cc0000;"></span>Course 4:
    </th>
           <td class="align-left"><input name="grade4" type="text" id="grade4" size="10" onBlur="validgradecheck" /> </td>
     <td class="align-left"><input type="text" name="credit4" id="credit4" size="10" /></td>
        </tr>
  <tr>
           <th class="right-align">
              <span style="color:#cc0000;"></span>Course 5:
           </th>
           <td class="align-left"><input type="text" name="grade5"  id="grade5" size="10" onBlur="validgradecheck" /></td>
     <td class="align-left"><input type="text" name="credit5" id="credit5" size="10" /></td>
        </tr>
  <tr>
           <th class="right-align">
              <span style="color:#cc0000;"></span>Course 6:
           </th>
           <td class="align-left"><input type="text" name="grade6" id="grade6" size="10"  onBlur="validgradecheck"/></td>
     <td class="align-left"><input type="text" name="credit6" id="credit6" size="10" /></td>
        </tr>
        
        <tr>
           <td class="right-align">
             <input name="button" type="button" value="Calculate GPA" onClick="gpacalc()"/>
        </td>
           <td class="align-left">
             <input name="Reset" type="reset" />
     </td>
        </tr>
  <tr>
           <td class="right-align">
              <span style="font-weight:bolder;">GPA:</span>
           </td>
           <td><input type="text" name="gpacalc" id="gpacalc" value=" " size="10" /></td>
        </tr>
        
    
  </table>
</form>
</div>
<div id="displayDateLast">
</div>
</body>
</html>
Hannah.S
  • 37
  • 5
  • _You get as good quality of answers as you do for effort you put into the question_ – q.Then Apr 16 '17 at 02:49
  • 1
    What more did I need to put into it? I gave all of my code every bit and the edited it later to show snippets of just the javascript section and css section by themselves to make it easier to look over. I also put what I wanted the code to do and what problems I am having with it? I don't understand how else I'm suppose to ask questions on here to get answers?? – Hannah.S Apr 16 '17 at 03:16
  • This is just my opinion, and I don't mean to be presumptuous, but I think this question is overly broad, you've asked a lot of things and said you had troubles with implementing stuff, but I don't see where you were specific about that. Yes, you did provide code, but it's way too much and doesn't elaborate on much (which does what, comment wise, what you have problems with). It's a bit hard for people to jump in and help – q.Then Apr 16 '17 at 03:24

1 Answers1

1

Few remarks:

  • I don't think you need to worry about old browsers as no one should be using them nowadays. Therefore, <!--Hide from old browsers --> not needed.
  • What's the point of calculating the GPA when the page loads i.e. onload? There are no grades when the page loads up, so you'll always get an error. It is probably better to only calculate when the user clicks the button.
  • Do not repeat yourself.
  • Do not write for yourself to only read but for others, so comment your code.
  • Check this answer on the difference between dot notation and square brack notation when it comes to accessing an object property.
  • eval() is evil and not needed in your code.

Here's how I would do it (hopefully it answers all your questions):

// an object is a better data structure for storing grading scale
var gradingScale = {
  'A+': 4,
  'A': 4,
  'A-': 3.7,
  'B+': 3.3,
  'B': 3,
  'B-': 2.7,
  'C+': 2.3,
  'C-': 1.7,
  'D+': 1.3,
  'D': 1,
  'D-': 0.7,
  'F': 0.0
};

// note in JS, you can reference an element by their ID
// attaching onclick event handler to your button with ID "gpacalc"
gpacalc.onclick = function() {
  var totalGradePoints = 0;
  var totalCredits = 0;
  // easier to just start at 1
  for (var i = 1; i <= 6; i++) {
    // you can access an object's property using [] notation; useful in this situation
    // good idea to normalize your values e.g. trim, uppercase, etc
    var grade = document.calcGpaForm['grade' + i].value.trim().toUpperCase();
    var credit = document.calcGpaForm['credit' + i].value.trim();
    // skip if no grade is entered
    if (grade == "") {
      break;
    }
    // check if grade is invalid i.e. not in the grading scale
    if (!gradingScale.hasOwnProperty(grade)) {
      alert("'" + grade + "' is not a valid letter grade. Course " + i + ".");
      return;
    // check if credit is empty
    } else if (credit == "") {
      alert("You left the number of credits blank for Course " + i + ".");
      return;
    // check if credit is not a number
    } else if (isNaN(credit)) {
      alert("Enter a valid number of credits for Course " + i + ".");
      return;
    }
    // at this point, the grade and credit should both be valid...
    credit = parseInt(credit, 10);
    // so let's add them to the tally
    totalGradePoints += gradingScale[grade] * credit;
    totalCredits += credit;
  }
  // check if total credits is greater than zero
  if (totalCredits == 0) {
    alert("Total credits cannot equal zero.");
    return;
  }
  // show total
  gpa.value = Math.round((totalGradePoints / totalCredits) * 10) / 10;
}
<form name="calcGpaForm" method="post">
  <table>
    <tr>
      <h4 style="text-align: center">Letter Grade:</h4>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 1:
      </th>
      <td class="align-left"><input type="text" name="grade1" type="text" id="grade1" size="10"></td>
      <td class="margin-left: auto"><input type="text" name="credit1" id="credit1" size="10"></td>
    </tr>
    <tr>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 2:
      </th>
      <td class="align-left"><input name="grade2" type="text" id="grade2" size="10"></td>
      <td class="align-left"><input type="text" name="credit2" id="credit2" size="10"></td>
    </tr>
    <tr>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 3:
      </th>
      <td class="align-left"><input name="grade3" type="text" id="grade3" size="10"></td>
      <td class="align-left"><input type="text" name="credit3" id="credit3" size="10"></td>
    </tr>
    <tr>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 4:
      </th>
      <td class="align-left"><input name="grade4" type="text" id="grade4" size="10"></td>
      <td class="align-left"><input type="text" name="credit4" id="credit4" size="10"></td>
    </tr>
    <tr>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 5:
      </th>
      <td class="align-left"><input type="text" name="grade5" id="grade5" size="10"></td>
      <td class="align-left"><input type="text" name="credit5" id="credit5" size="10"></td>
    </tr>
    <tr>
      <th class="right-align">
        <span style="color:#cc0000;"></span>Course 6:
      </th>
      <td class="align-left"><input type="text" name="grade6" id="grade6" size="10"></td>
      <td class="align-left"><input type="text" name="credit6" id="credit6" size="10"></td>
    </tr>

    <tr>
      <td class="right-align">
        <input type="button" value="Calculate GPA" id="gpacalc">
      </td>
      <td class="align-left">
        <input name="Reset" type="reset">
      </td>
    </tr>
    <tr>
      <td class="right-align">
        <span style="font-weight:bolder;">GPA:</span>
      </td>
      <td><input type="text" id="gpa" value="" size="10"></td>
    </tr>
  </table>
</form>

(Note: the sample attaches an onclick event handler to your button in the JS and not by using an onclick attribute. Though, the latter way should work.)

Community
  • 1
  • 1
Mikey
  • 6,728
  • 4
  • 22
  • 45
  • Thank you! I see what you guys are saying I should make comments in my code to make it easier to read and follow. It certainly made it easier for me to read your code. I'll try to be more specific with my questions. However, I have problem using this code you made for some reason. I can tell it definitely works by running the code snippet on here but when I try to copy and use it in a saved .html file it doesn't work? As in when I enter a letter grade and credit number and then press calculate GPA nothing happens. There is also no alert either if I enter an invalid letter grade. – Hannah.S Apr 16 '17 at 16:22
  • There is also no alert for an invalid credit score. I made sure to put the Javascript section in its proper place and start and end tags. So I'm not sure why this doesn't work like it does here? – Hannah.S Apr 16 '17 at 16:27
  • Did you copy the JavaScript **and** the HTML in its entirety? Particularly, in the HTML, I gave an ID `gpacalc` to your button and an ID `gpa` to your last textbox. Your code should be somewhat similar to [this](https://pastebin.com/raw/g4dXvpeS) (which I have just tested and works). – Mikey Apr 16 '17 at 16:45
  • hmm I did it seems to work if I only open it directly from the file its self, which takes it to internet explorer. However, if I try to open it and specify how I want to open it (like with Internet Explorer, Chrome etc,) it doesn't work? Anyway at least I can view it working one way and that's good enough for me (it could just be my crappy computer though idk). Thanks for help! :) – Hannah.S Apr 16 '17 at 17:11