Search code examples
javascripthtmlcssformsletters

GPA Calculator, how to make letter inputs into numbers


I am trying to make a simple GPA calculator. There are 4 forms and I'm trying to make it so a user enters 4 letters (A,B,C,D, or F) and have each of those numbers represent a value (A = 4.0, B=3.0 ect.) And basically just get the average of them all. Right now I just made it so it so it works if the user enters numbers, but now I want to change it so the user enters the letter grades and get the same gpa number. I have no idea how to do this. Please help thank you.

(This is my html)

<!DOCTYPE html>
    <html>
        <head>
            <title>GPA Calculator</title>
            <link type="text/css" rel="stylesheet" href="project6.css">
            <script type="text/javascript" src="project6.js"></script>
        </head>
        <body>
            <h1>Enter Your Grades Below</h1>
            <form name="form" id="form">
                <br>
                <input type="text" class="textForm1" name="textForm1"></input><br>
                <input type="text" class="textForm1" name="textForm2"></input><br>
                <input type="text" class="textForm1" name="textForm3"></input><br>
                <input type="text" class="textForm1" name="textForm4"></input><br>
                <button type="button" onClick="getGrade()">Submit</button>
            </form>
            <div id="div">
            </div>
        </body>
    </html>

(This is my javascript)

var getGrade = function() {
    var inputOne = document.form.textForm1.value;
    var inputTwo = document.form.textForm2.value;
    var inputThree = document.form.textForm3.value;
    var inputFour = document.form.textForm4.value;
    document.getElementById("div").innerHTML = (Number(inputOne) + Number(inputTwo) + Number(inputThree) + Number(inputFour))/4;
}

Solution

  • I read all the answers and all gave me different ideas of what to do, but in the end, I followed mostly what Mike C. did, but not exactly the same way. Here's what I ended up with that worked perfectly.

    var gradeValues = {
        "A": 4.0,
        "B": 3.0,
        "C": 2.0,
        "D": 1.0,
        "F": 0
    };
    var getGrade = function() {
        input1 = document.form.input1.value;
        input2 = document.form.input2.value;
        input3 = document.form.input3.value;
        input4 = document.form.input4.value;
        document.getElementById("result").innerHTML = ((gradeValues[input1] + gradeValues[input2] + gradeValues[input3] + gradeValues[input4]) / 4) + " is your GPA";
    };