计算GPA和学分

时间:2017-04-15 17:20:39

标签: javascript html



<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>
&#13;
<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>
&#13;
&#13;
&#13;

我试图建立一个网页,允许用户输入4到6年级的任何课程。在字母等级旁边,我想要一个接受课程学分的文本字段。此外,当单击计算GPA按钮时,我希望它确认已输入字母等级,然后累积成绩点和学分时间并显示GPA。虽然我在计算GPA时遇到了麻烦。当用户输入除字母等级以外的任何内容时,还有警报显示?有人可以查看我的代码并告诉我应该修复或添加的内容吗?如果您阅读本文并尝试提供帮助,谢谢!

&#13;
&#13;
<!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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

几点评论:

  • 我认为您不必担心旧浏览器,因为现在没有人应该使用它们。因此,<!--Hide from old browsers -->不需要。
  • 当页面加载onload时,计算GPA的重点是什么?页面加载时没有等级,因此您总是会收到错误。最好只计算用户点击按钮的时间。
  • Do not repeat yourself
  • 请勿为自己写作,只为其他人阅读,所以请注释您的代码。
  • 在访问对象属性时,请在difference between dot notation and square brack notation上查看此答案。
  • eval() is evil,您的代码中不需要。

这是我将如何做到的(希望它能回答你所有的问题):

&#13;
&#13;
// 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;
}
&#13;
<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>
&#13;
&#13;
&#13;

(注意:示例会将一个onclick事件处理程序附加到JS中的按钮,而不是使用onclick属性。但后一种方法应该有效。)