3

New to JavaScript and trying to create a tuition calculator. I need to know residency, if they will take an on campus class, and credit hours, then tuition is calculated. I cannot get the if else statement to work. The code is only showing for an on campus class but once this works I will add online classes etc. Thank you for any help!

I have this calculator working if I ask the residency question before each class type but I want to ask the residency question only once and then assign tuition to var onctut2. I would also like for students to be able to input a decimal for onchours1 but I could only get whole numbers to work. I have tried various if else statements.

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Tuition Calculator</title>
    <script type="text/javascript">// <![CDATA[
    function formHandler(form) {
     var residency = eval(form.residency.value);
        var onctut1 = eval(form.onctut1.value);
        var onchours1 = eval(form.onchours1.value);
     var onctut2 = 0;
        var t1 = onctut2 * onchours1;
        var totalhours = onchours1;
        var oncfee1 = 0;
        var techfee1 = 0;
        var strecfee = 0;
            //Calculate on campus tut
            if (residency == "yes") && (onctut1 == "yes") {
              onctut2 = 252.00;
            } else if (residency == "no") && (onctut1 == "yes") {
              onctut2 = 554.00;
            } else {
              onctut2 = 0;
            }
            //Calculate on campus fees
            if (onchours1 == "1") {
              oncfee1 = 75.25;
            } else if (onchours1 == "2") {
              oncfee1 = 87.5;
            } else if (onchours1 == "3") {
              oncfee1 = 99.75;
            } else if (onchours1 == "4") {
              oncfee1 = 169.5;
            } else if (onchours1 == "5") {
              oncfee1 = 181.75;
            } else if (onchours1 == "6") {
              oncfee1 = 194.0;
            } else if (onchours1 == "7") {
              oncfee1 = 433.25;
            } else if (onchours1 == "8") {
              oncfee1 = 445.5;
            } else if (onchours1 == "9") {
              oncfee1 = 457.75;
            } else if (onchours1 == "10") {
              oncfee1 = 470.0;
            } else if (onchours1 == "11") {
              oncfee1 = 482.25;
            } else if (onchours1 == "12") {
              oncfee1 = 494.5;
            } else if (onchours1 == "13") {
              oncfee1 = 506.75;
            } else if (onchours1 == "14") {
              oncfee1 = 519.0;
            } else if (onchours1 == "15") {
              oncfee1 = 531.25;
            } else if (onchours1 == "16") {
              oncfee1 = 543.5;
            } else {
              oncfee1 = 0;
            }
     //Calculate on tech fee
            if (totalhours == "1") {
              techfee1 = 11.;
            } else if (totalhours == "2") {
              techfee1 = 22.;
            } else if (totalhours == "3") {
              techfee1 = 33.;
            } else if (totalhours == "4") {
              techfee1 = 44.;
            } else if (totalhours == "5") {
              techfee1 = 55.;
            } else if (totalhours == "6") {
              techfee1 = 66.;
            } else if (totalhours == "7") {
              techfee1 = 77.;
            } else if (totalhours == "8") {
              techfee1 = 88.;
            } else if (totalhours == "9") {
              techfee1 = 99.;
            } else if (totalhours == "10") {
              techfee1 = 110.;
            } else if (totalhours == "11") {
              techfee1 = 121.;
            } else if (totalhours == "12") {
              techfee1 = 132.;
            } else if (totalhours == "13") {
              techfee1 = 143.;
            } else if (totalhours == "14") {
              techfee1 = 154.;
            } else if (totalhours == "15") {
              techfee1 = 165.;
            } else if (totalhours == "16") {
              techfee1 = 165.;
            } else {
              techfee1 = 0;
            }
            //Calculate on student rec fee
            if (totalhours > "0") {
              strecfee = 4;
            }
        var fees1 = oncfee1;
     var fees = fees1 + techfee1 + strecfee;
        var cost = t1 + fees;
        form.t1.value = "$" + t1.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.fees.value = "$" + fees.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.costresult.value = "$" + cost.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
     form.totalhours.value = "" + totalhours;
    }
    // ]]></script>
    </head>
    <body>
    <form method="post" name="testform">
      <div>
        <table
              id="AutoNumber1"
              summary="calculate the cost per semester for 
        graduate students"
            >
          <tbody>
            <tr>
              <td colspan="2"><label for="residency">Are you a Resident? </label>
                <select id="residency" name="residency">
                  <option selected="selected" value="0"> </option>
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
                <select id="onctut1" name="onctut1">
                  <option selected="selected" value="0"> </option>
                  <option value="yes">Yes</option>
                  <option value="no">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
                <select id="onchours1" name="onchours1">
                  <option selected="selected" value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td colspan="2"><button
                        name="CostResult"
                        onclick="javascript:formHandler(this.form)"
                        type="button"
                      > Calculate Cost </button></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td><label for="t1">Tuition On Campus Class(es) </label></td>
              <td><input id="t1" name="t1" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="fees">Fees </label></td>
              <td><input id="fees" name="fees" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
              <td><input
                      id="costresult"
                      name="costresult"
                      size="10"
                      type="text"
                    /></td>
            </tr>
            <tr>
              <td><label for="totalhours">Total Credit Hours </label></td>
              <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
            </tr>
          </tbody>
        </table>
      </div>
    </form>
    </body>
    </html>

When I click "Calculate Cost" the form remains blank.

Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
Effy
  • 35
  • 4
  • 1
    You should use a [`switch` statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch). – Scott Marcus Jul 24 '19 at 19:33
  • I looked at the switch statement but was not sure how to apply it to my issue. – Effy Jul 24 '19 at 19:37
  • This is tangential, but using eval in this context is not recommended. It would allow javascript to be entered in the form fields and executed directly in the page context. Trying entering alert("yo") into one of the fields and submitting the form. Using Number(form.onchours1.value) is better. – Rondo Jul 24 '19 at 20:01
  • @Rondo Using `eval` in any context is not recommended. In 25 years with JavaScript, I've never come across a use case that couldn't be solved without it. – Scott Marcus Jul 24 '19 at 20:10
  • Then follow the link I shared and investigate it. It's very simple. – Scott Marcus Jul 24 '19 at 20:10
  • 1
    Thanks for the suggestion @Rondo I have removed eval. Scott Marcus I will try your suggestion again. I'm not a programmer so I am thankful for the help! – Effy Jul 24 '19 at 20:30
  • @ScottMarcus since you pinged me about it... I too have been using JS a long time: since it was introduced in browsers and since Netscape's Server-Side Javascript product in the mid 90's. In the browser context which is the scope of this question, I agree eval is not nec. But, while it is out of scope for this question, there are use cases, like code storage, in controlled environments, in which eval() usage is a critical and necessary component and it is both valuable and safe. – Rondo Jul 26 '19 at 19:04
  • @Rondo I wouldn't even use `eval()` for code storage. I'd use JSON for the storage format and then `JSON.parse()` when the code is extracted. As I say, I've never encountered a use case where `eval()` is required. 99% of the time, the proposed solution that has `eval()` in it is just the wrong approach to solving the problem and reworking the solution will eliminate the need for it. – Scott Marcus Jul 29 '19 at 12:19
  • @ScottMarcus JSON.parse() does not execute javascript code. How would you save javascript code in JSON without executing eval()? – Rondo Jul 30 '19 at 00:33
  • @Rondo Yes, `JSON.parse()` [can execute code](https://stackoverflow.com/questions/40875630/javascript-save-object-with-methods-as-a-string/40876342#40876342). You must use "replacer" and "reviver" methods with it. Using `JSON.parse()` is safer than `eval()` because of automatic scrubbing that it performs and it's more efficient as well. – Scott Marcus Jul 30 '19 at 18:17

4 Answers4

3
if (residency == "yes") && (onctut1 == "yes") {
    onctut2 = 252.00;
} else if (residency == "no") && (onctut1 == "yes") {
    onctut2 = 554.00;
} else {
    onctut2 = 0;
}

My guess is that the problem with this is that you need to put the parentheses around the whole condition, not each individual condition.

if (residency == "yes" && onctut1 == "yes") {
    onctut2 = 252.00;
} else if (residency == "no" && onctut1 == "yes") {
    onctut2 = 554.00;
} else {
    onctut2 = 0;
}

It also looks like you could simplify your code instead of using that huge set of if statements for the techfee1 variable, you could do something like:

totalhours = +totalhours; // convert it to a number
techfee1 = totalhours * 11;
if (totalhours === 16) {
    techfee1 = 165;
}
if (totalhours > 16 || totalhours < 1) {
    techfee1 = 0;
}
Miles Grover
  • 609
  • 3
  • 5
  • Thank you for the tip on the techfee1, works great. I still can't get my var t1 to work. – Effy Jul 24 '19 at 20:25
2

Three types of issues are throwing errors in the console:
1) Conditions specified by if statements must be wrapped in parentheses (in their entirety), so for example, either:
if (residency == "yes" && onctut1 == "yes")
or
if ( (residency == "yes") && (onctut1 == "yes") ).

2) The eval function (which should generally be avoided whenever possible) expects to receive valid JavaScript code. Removing the eval call resolves this.

3) The > operator expects numbers, not strings. Wrapping the comparison in the parseInt function fixes this.

Here's a working version with these changes implemented:

*--EDITED--
My original answer made only the above changes.
This revised version reworks and simplifies the code and provides clearer variable naming.
(I haven't fully tested it, so I'm not sure I got all the math right, but the most you should have to do to update it is change a few numbers.)
*-- --

function formHandler(form) {
  
  // Gets form inputs
  var residencyInput = form.residency.value,
      oncTutInput = form.onctut1.value,
      oncHoursInput = form.onchours1.value;
  
  // Converts each input (from String) to Boolean or Number (assumes valid input values)
  var residencyBoolean = (residencyInput == "Yes"),
      oncTutBoolean = (oncHoursInput == "Yes"),
      oncHoursNumber = parseInt(oncHoursInput);

  // Sets Hourly onc tut based on residency
  if(residencyBoolean){ oncTutHourly = 252.00; }
  else{ oncTutHourly = 554.00; }

  // Calculates onc fees (defaults to zero, won't change unless onHoursNumber is positive)
  let oncFee = 0;
  if(oncHoursNumber > 0 && oncHoursNumber < 4){
    oncFee = oncHoursNumber * 12.25 + 63;
  }
  else if(oncHoursNumber > 3 && oncHoursNumber < 7){
    oncfee = oncHoursNumber * 12.25 + 120.5;
  }
  else if(oncHoursNumber > 6 && oncHoursNumber < 17){
    oncfee = oncHoursNumber * 12.25 + 347.5;
  }

  // Calculates tech fee (defaults to zero, won't change unless onHoursNumber is positive)
  let techFee = 0;
  // If `oncHoursNumber` is above 15, techfee1 will be 165
  if(oncHoursNumber > 0){
    techfee = Math.min(oncHoursNumber * 11, 165);
  }

  //Calculates student rec fee
  let strecFee = 0;
  if(oncHoursNumber > "0"){ strecFee = 4; }
  
  // Calculates final values
  let oncTutTotal = oncHoursNumber * oncTutHourly; 
  let feesTotal = oncFee + techFee + strecFee;
  let costTotal =  oncTutTotal + feesTotal;

  form.t1.value = "$" + oncTutTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.fees.value = "$" + feesTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.costresult.value = "$" + costTotal.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
  form.totalhours.value = "" + oncHoursNumber;
}
<form method="post" name="testform">
  <div>
    <table
          id="AutoNumber1"
          summary="calculate the cost per semester for 
    graduate students"
        >
      <tbody>
        <tr>
          <td colspan="2"><label for="residency">Are you a Resident? </label>
            <select id="residency" name="residency">
              <option selected="selected" value="0"> </option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
            <select id="onctut1" name="onctut1">
              <option selected="selected" value="0"> </option>
              <option value="yes">Yes</option>
              <option value="no">No</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
            <select id="onchours1" name="onchours1">
              <option selected="selected" value="0">0</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
              <option value="5">5</option>
              <option value="6">6</option>
              <option value="7">7</option>
              <option value="8">8</option>
              <option value="9">9</option>
              <option value="10">10</option>
              <option value="11">11</option>
              <option value="12">12</option>
              <option value="13">13</option>
              <option value="14">14</option>
              <option value="15">15</option>
              <option value="16">16</option>
            </select></td>
        </tr>
        <tr>
          <td colspan="2"><br></td>
        </tr>
        <tr>
          <td colspan="2"><button
                    name="CostResult"
                    onclick="javascript:formHandler(this.form)"
                    type="button"
                  > Calculate Cost </button></td>
        </tr>
        <tr>
          <td colspan="2"><br></td>
        </tr>
        <tr>
          <td><label for="t1">Tuition On Campus Class(es) </label></td>
          <td><input id="t1" name="t1" size="10" type="text" /></td>
        </tr>
        <tr>
          <td><label for="fees">Fees </label></td>
          <td><input id="fees" name="fees" size="10" type="text" /></td>
        </tr>
        <tr>
          <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
          <td><input
                  id="costresult"
                  name="costresult"
                  size="10"
                  type="text"
                /></td>
        </tr>
        <tr>
          <td><label for="totalhours">Total Credit Hours </label></td>
          <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
        </tr>
      </tbody>
    </table>
  </div>
</form>
Cat
  • 4,141
  • 2
  • 10
  • 18
  • Thank you for your help. Everything is working except my var t1 which displays tuition. I am trying to see how to use the switch statement as mentioned above and apply it to my issue. Thanks so much! – Effy Jul 24 '19 at 20:46
2

I think I've got your T1 issue hammered out and I think it's working how you're wanting!

 <!doctype html>
    <html>
    <head>
    <meta charset="utf-8" />
    <title>Tuition Calculator</title>
    <script type="text/javascript">// <![CDATA[
    function formHandler(form) {
     var residency = eval(form.residency.value);
        var onctut1 = eval(form.onctut1.value);
        var onchours1 = eval(form.onchours1.value);
       var onctut2 = 0;
        var totalhours = onchours1;
        var oncfee1 = 0;
        var techfee1 = 0;
        var strecfee = 0;
            //Calculate on campus tut
            if (residency == 0 && onctut1 == 0) {
              onctut2 = 252.00;
            } else if (residency == 1 && onctut1 == 0) {
              onctut2 = 554.00;
            } else {
              onctut2 = 0;
            }
            //Calculate on campus fees
            if (onchours1 == "1") {
              oncfee1 = 75.25;
            } else if (onchours1 == "2") {
              oncfee1 = 87.5;
            } else if (onchours1 == "3") {
              oncfee1 = 99.75;
            } else if (onchours1 == "4") {
              oncfee1 = 169.5;
            } else if (onchours1 == "5") {
              oncfee1 = 181.75;
            } else if (onchours1 == "6") {
              oncfee1 = 194.0;
            } else if (onchours1 == "7") {
              oncfee1 = 433.25;
            } else if (onchours1 == "8") {
              oncfee1 = 445.5;
            } else if (onchours1 == "9") {
              oncfee1 = 457.75;
            } else if (onchours1 == "10") {
              oncfee1 = 470.0;
            } else if (onchours1 == "11") {
              oncfee1 = 482.25;
            } else if (onchours1 == "12") {
              oncfee1 = 494.5;
            } else if (onchours1 == "13") {
              oncfee1 = 506.75;
            } else if (onchours1 == "14") {
              oncfee1 = 519.0;
            } else if (onchours1 == "15") {
              oncfee1 = 531.25;
            } else if (onchours1 == "16") {
              oncfee1 = 543.5;
            } else {
              oncfee1 = 0;
            }
     //Calculate on tech fee
            if (totalhours == "1") {
              techfee1 = 11.;
            } else if (totalhours == "2") {
              techfee1 = 22.;
            } else if (totalhours == "3") {
              techfee1 = 33.;
            } else if (totalhours == "4") {
              techfee1 = 44.;
            } else if (totalhours == "5") {
              techfee1 = 55.;
            } else if (totalhours == "6") {
              techfee1 = 66.;
            } else if (totalhours == "7") {
              techfee1 = 77.;
            } else if (totalhours == "8") {
              techfee1 = 88.;
            } else if (totalhours == "9") {
              techfee1 = 99.;
            } else if (totalhours == "10") {
              techfee1 = 110.;
            } else if (totalhours == "11") {
              techfee1 = 121.;
            } else if (totalhours == "12") {
              techfee1 = 132.;
            } else if (totalhours == "13") {
              techfee1 = 143.;
            } else if (totalhours == "14") {
              techfee1 = 154.;
            } else if (totalhours == "15") {
              techfee1 = 165.;
            } else if (totalhours == "16") {
              techfee1 = 165.;
            } else {
              techfee1 = 0;
            }
            //Calculate on student rec fee
            if (totalhours > "0") {
              strecfee = 4;
            }
        var fees1 = oncfee1;
       var fees = fees1 + techfee1 + strecfee;
        var t1 = onctut2 * onchours1;
        var cost = t1 + fees;
        form.t1.value = "$" + t1.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.fees.value = "$" + fees.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
        form.costresult.value = "$" + cost.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
     form.totalhours.value = "" + totalhours;
    }
    // ]]></script>
    </head>
    <body>
    <form method="post" name="testform">
      <div>
        <table
              id="AutoNumber1"
              summary="calculate the cost per semester for 
        graduate students"
            >
          <tbody>
            <tr>
              <td colspan="2"><label for="residency">Are you a Resident? </label>
                <select id="residency" name="residency">
                  <option selected="selected" value="0"> </option>
                  <option value="0">Yes</option>
                  <option value="1">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onctut1">Will you take an On campus class? </label>
                <select id="onctut1" name="onctut1">
                  <option selected="selected" value="0"> </option>
                  <option value="0">Yes</option>
                  <option value="1">No</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><label for="onchours1">Select On campus class Credit Hours </label>
                <select id="onchours1" name="onchours1">
                  <option selected="selected" value="0">0</option>
                  <option value="1">1</option>
                  <option value="2">2</option>
                  <option value="3">3</option>
                  <option value="4">4</option>
                  <option value="5">5</option>
                  <option value="6">6</option>
                  <option value="7">7</option>
                  <option value="8">8</option>
                  <option value="9">9</option>
                  <option value="10">10</option>
                  <option value="11">11</option>
                  <option value="12">12</option>
                  <option value="13">13</option>
                  <option value="14">14</option>
                  <option value="15">15</option>
                  <option value="16">16</option>
                </select></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td colspan="2"><button
                        name="CostResult"
                        onclick="javascript:formHandler(this.form)"
                        type="button"
                      > Calculate Cost </button></td>
            </tr>
            <tr>
              <td colspan="2"><br></td>
            </tr>
            <tr>
              <td><label for="t1">Tuition On Campus Class(es) </label></td>
              <td><input id="t1" name="t1" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="fees">Fees </label></td>
              <td><input id="fees" name="fees" size="10" type="text" /></td>
            </tr>
            <tr>
              <td><label for="costresult">Total Estimated Tuition/Fees Semester Cost </label></td>
              <td><input
                      id="costresult"
                      name="costresult"
                      size="10"
                      type="text"
                    /></td>
            </tr>
            <tr>
              <td><label for="totalhours">Total Credit Hours </label></td>
              <td><input id="totalhours" name="totalhours" size="10" type="text" /></td>
            </tr>
          </tbody>
        </table>
      </div>
    </form>
    </body>
    </html>
Tori
  • 75
  • 10
  • Thanks Tori! It must have been a formatting issue with the var t1 as I couldn't get it to work yesterday. I really appreciate you following up! – Effy Jul 25 '19 at 14:31
  • No problem! Can you mark with the green check that this solved the problem for you? :) – Tori Jul 25 '19 at 16:01
0

I would honestly use a switch statement instead. It makes more sense than having multiple conditions in an if/else. https://www.w3schools.com/js/js_switch.asp

//Calculate on campus tut
        if (residency == 0 && onctut1 == 0) {
          onctut2 = 252.00;
        } else if (residency == 1 && onctut1 == 0) {
          onctut2 = 554.00;
        } else {
          onctut2 = 0;
        }
Tori
  • 75
  • 10
  • I looked at the switch statement but was not sure how to apply it to my issue. – Effy Jul 24 '19 at 19:34
  • 1
    To do it how you're doing it, first you'll want to not pass "yes" and "no" as values in your form. If you do that, you can change this chunk that I've added in my answer and it will start to calculate. It might need some tweaking from there, but that should be a start. – Tori Jul 24 '19 at 19:43
  • Now everything is working except var t1 = onctut2 * onchours1; getting closer, thanks! – Effy Jul 24 '19 at 19:56