1

I am trying to write a small javascript program that will do 3 things, 1. it will determine if a number is odd or even and display that result on the webpage, 2. calculate a letter grade based on a number entered on the webpage via a switch statement, and 3. reset the form based on the press of the button.

The odd and even part and reset part seem to work ok but the grade switch statement is not working. It doesn't seem to be displaying the letter grade that corresponds to the value entered. I tried looking at the error but have not had much luck. Any help is appreciated.

 <!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>WDV221 Intro Javascript</title>
        <script src="Odd_Even_Grades.js"></script>
    </head>

    <body>
        <h2>WDV221 Intro Javascript</h2>
        <h3>Comparisons and IF Statements - Odds Evens and Grades</h3>
        <hr />
        <p></p>
        <hr />
        <form id="form1" name="form1" method="post" action="">
            <p>Value 1:
                <input type="text" name="Value1" id="Value1" />
            </p>
            <p>Result: <span id="Result"></span></p>
            <p>
                <input type="button" value="Is it Odd or Even?" onclick="OddEven()"/>
            </p>
            <p>
            </p>
            <h4>Enter the percentage that you have achieved:</h4>
            <p> Percentage:
                <input type="text" name="percent" id="percent" />
            </p>
            <p>Grade: <span id="Score"></span></p>
            <p>
                <input type="button" value="Calculate Grade" onclick="ConvertGrade()"/>
            </p>
            <p>
                <input type="button" name="Reset" id="button" value="Reset" onclick="ResetForm()"/>
            </p>
        </form>

        <p>Instructions:</p>
        <ol>
            <li>You are asked to create a working example in Javascript based upon the two given problems.</li>
            <li>For each problem you have two deliverables:</li>
            <li>Pseudo code algorithm and test plan.</li>
            <li>A working example using Javascript.</li>
            <li>The two problems you have been asked to resolve:</li>
            <li>Get an input value, verify that it is a number, if it is a number determine whether it is even or odd.</li>
            <li>Find the letter grade based upon the percentage grade.   example: 54% is an 'F', 88% is a 'B', etc. This would be a good one to consider using a switch statement.</li>
        </ol>
    </body>
</html>

    function ResetForm()
{
    document.getElementById("form1").reset();
    document.getElementById("Result").innerHTML = "";
    document.getElementById("Grade").innerHTML;
}

function OddEven() {
    //read in entered values from text fields
    var Num1 = document.getElementById("Value1").value;

        if (Num1 % 2 == 0)
        {
            document.getElementById("Result").innerHTML = "Even";
        }
        else
        {
            document.getElementById("Result").innerHTML = "Odd";
        }
}

function ConvertGrade()
{

    var grade = document.getElementById("percent").value;

    {
        case (grade >= 93.0 && grade <= 100):
            LetterGrade = "A";
            break;
        case (grade >= 92.9 && grade <= 90.0):
            LetterGrade = "A-";
            break;
        case (grade >= 89.9 && grade <= 87.0):
            LetterGrade = "B+";
            break;
        case (grade >= 86.9 && grade <= 83.0):
            LetterGrade = "B";
            break;
        case (grade >= 82.9 && grade <= 80.0):
            LetterGrade = "B-";
            break;
        case (grade >= 79.9 && grade <= 70.0):
            LetterGrade = "C";
            break;
        case (grade >= 69.9 && grade <= 60.0):
            LetterGrade = "D";
            break;
        case (grade >= 59.9 && grade <= 0):
            LetterGrade = "F";
            break;
        default:
            LetterGrade = "Enter valid Number"
    }
    document.getElementById("score").innerHTML = LetterGrade;

}
kjblkblt
  • 11
  • 3

3 Answers3

2

There are several issues with your code:

  • As @rlemon has pointed out, you have a span with id="Score" but you try to find it under score (note the letter case) in ConvertGrade() and under Grade in ResetForm().

  • The switch statement is missing the switch keyword and the corresponding expression. I guess you wanted to use switch (true).

  • The conditions in each case inside the switch are the other way around:

grade >= 92.9 && grade <= 90.0
// no number is greater than 92.9 and smaller than 90.0
  • If you are using <= and >= it is pointless to set the limits in 93 and 92.9. Instead, do >= 93 and < 93.

  • Actually, you don't need event that. You are using the break statement, so it is not necessary to set the upper and lower limit on each case. Set just the lower one.

  • There is no validation for the data provided in Value1 to check if the value is actually a number. (thank you @A.Meshu)

  • You are not cleaning the score element in ResetForm() (I already pointed out that you named it Grade, now I mean that you forgot = '' after innerHTML.

One extra tip. There are several conventions to write the name of HTML attributes and JavaScript variables. I'm not going to recommend you any. I just advise you to choose one and stick to it. It will save you headaches in the future.

Your code should look afterwards like in the snippet below:

function ResetForm() {
  document.getElementById("form1").reset();
  document.getElementById("Result").innerHTML = "";
  document.getElementById("score").innerHTML = "";
}

function OddEven() {
  //read in entered values from text fields
  var Num1 = document.getElementById("Value1").value;

  if (Number.isInteger(+Num1)) {
    if (Num1 % 2 == 0) {
      document.getElementById("Result").innerHTML = "Even";
    } else {
      document.getElementById("Result").innerHTML = "Odd";
    }
  } else {
    document.getElementById("Result").innerHTML = "Not a integer";
  }
}

function ConvertGrade() {
  var grade = document.getElementById("percent").value;

  switch (true) {
    case (grade >= 93.0):
      LetterGrade = "A";
      break;
    case (grade >= 90.0):
      LetterGrade = "A-";
      break;
    case (grade >= 87.0):
      LetterGrade = "B+";
      break;
    case (grade >= 83.0):
      LetterGrade = "B";
      break;
    case (grade >= 80.0):
      LetterGrade = "B-";
      break;
    case (grade >= 70.0):
      LetterGrade = "C";
      break;
    case (grade >= 60.0):
      LetterGrade = "D";
      break;
    case (grade >= 0):
      LetterGrade = "F";
      break;
    default:
      LetterGrade = "Enter valid Number"
  }
  document.getElementById("score").innerHTML = LetterGrade;
}
<form id="form1" name="form1" method="post" action="">
  <p>Value 1:
    <input type="text" name="Value1" id="Value1" />
  </p>
  <p>Result: <span id="Result"></span></p>
  <p>
    <input type="button" value="Is it Odd or Even?" onclick="OddEven()" />
  </p>
  <p>
  </p>
  <h4>Enter the percentage that you have achieved:</h4>
  <p> Percentage:
    <input type="text" name="percent" id="percent" />
  </p>
  <p>Grade: <span id="score"></span></p>
  <p>
    <input type="button" value="Calculate Grade" onclick="ConvertGrade()" />
  </p>
  <p>
    <input type="button" name="Reset" id="button" value="Reset" onclick="ResetForm()" />
  </p>
</form>
David
  • 6,695
  • 3
  • 29
  • 46
  • Nice one. i would add to the odd/even conditions another "if" - in case the input is not a number at all. Right now it's pre define all strings as "odd". – A. Meshu Oct 30 '18 at 19:05
  • 1
    @A.Meshu - thank you, good catch. I would check if the input is an integer. Because odd/even makes sense just with integers and because to include other numeric types is both [tricky](https://stackoverflow.com/q/18082/5247200) and [subjective](https://github.com/jquery/jquery/issues/2960#issuecomment-212653472). That's why jQuery will deprecate `isNumeric()` in a future version. – David Oct 30 '18 at 20:13
0

I think your switch syntax is incorrect.

switch(expression) {
case x:
    code block
    break;
case y:
    code block
    break;
default:
    code block
}
Amit Bhoyar
  • 1,007
  • 5
  • 20
0

Other users have written about some of the other issues with your code so I won't repeat that, but I do want to write about your use of switch.

While you may have been advised that switch might make a good control here, for your purposes if conditions are much more suitable and shorter. switch has often been adapted for other cases (often seen where switch (true) and where the cases are tests against statements to be resolved, not single values like the documentation suggests), but I think it's wrong.

So here's a break down of how a series of if conditions can do a better job than a switch in this situation. Hope it's of some use.

// pick up the container elements
const q1 = document.querySelector('#q1');
const q2 = document.querySelector('#q2');

// attach change listeners to the input boxes
q1.querySelector('input').addEventListener('change', handleOddEven, false);
q2.querySelector('input').addEventListener('change', handlePercentage, false);

function oddEven(n) {

  // ternary operator which says
  // if the modulo of 2 is 0 return even, otherwise odd
  return n % 2 === 0 ? 'even' : 'odd';
}

function findLetterGrade(n) {
  let grade = 'A';

  // drop through the conditions to match the grade
  if (n <= 93) grade = 'A-';
  if (n <= 90) grade = 'B';
  if (n <= 87) grade = 'B-';
  if (n <= 83) grade = 'C';
  if (n <= 80) grade = 'D';
  if (n <= 70) grade = 'E';
  if (n <= 60) grade = 'F';
  return grade;
}

function handlePercentage() {

  // coerce the string value to a number
  const val = parseInt(this.value, 10);

  // add the returned result from findLetterGrade to the
  // textContent of the corresponding span
  q2.querySelector('span').textContent = findLetterGrade(val);
}

function handleOddEven() {
  const val = parseInt(this.value, 10);

  // is the value a number?
  const isNumber = !Number.isNaN(val);
  let txt;
  if (isNumber) {
    txt = `This is a number. It is ${oddEven(val)}`;
  } else {
    txt = 'This is not a number';
  }
  q1.querySelector('span').textContent = txt;
}
<div id="q1"><input type="text" placeholder="Add number" /><span></span></div>
<div id="q2"><input type="text" placeholder="Add percentage" /><span></span></div>
Andy
  • 61,948
  • 13
  • 68
  • 95