1

So, i'm trying to make a code that after submiting 3 notes it can calculate the average and the maximun note, but when trying to pass that data from my javascript function to a html paragraph the page just refreshes and doesn't show the result.

    function calculateAverage(){
    var maths = document.getElementById('nMaths').value;
    var language = document.getElementById('nLanguage').value;
    var history = document.getElementById('nHistory').value;
    var sumNotes = parseFloat(maths) + parseFloat(language) + parseFloat(history);
    var average = sumNotes / 3;
    var result = "Your average is " + average;
    document.getElementById('average').innerHTML = result;
}
<form id = "form" method="POST" action="notes.html">
    <div>
        <label> Enter maths note: </label>
        <input id = "nMaths">
    </div>
    <div>
        <label> Enter language note: </label>
        <input id = "nLanguage">
    </div>
    <div>
        <label> Enter history note: </label>
        <input id = "nHistory" type="numer">
    </div>
    <button onclick="calculateAverage()"> Calculate average </button>
    <button onclick="calculateBestNote()"> Calculate your best note </button>
</form>
<div>
    <p id = "average" name = "average"> Your average is: </p>
    <p id = "bestNote" name = "bestNote"> Your best note is: </p>
</div>
var result = "Your average is " + average;
document.getElementById('average').innerHTML = result;

}

  • The normal behavior of a `button` inside a `form` is to submit the form to the server. An easy way to prevent that is to use `type="button"`... That overides the default `type="submit"`. – Louys Patrice Bessette Apr 04 '21 at 15:46
  • Or [prevent the form from being submitted](https://stackoverflow.com/questions/8664486/javascript-code-to-stop-form-submission). – nosurs Apr 04 '21 at 15:54
  • Thanks for your time! I tried this but the form doesn't even submit if i add the type button... – matibohemio8 Apr 04 '21 at 15:56
  • You certainly have an error in console... `var maths = number(...)` should be `var maths = Number(...)` Notice the capital `N`. – Louys Patrice Bessette Apr 04 '21 at 16:03
  • Thanks foy your answer, i tried yesterday doing var maths = number(document.getElementById('nMaths').value); instead of var maths = document.getElementById('nMaths').value; and forgot to change back to the second one. But i tried changing the capital but still i'm having the same problem. Seems like the problem is how i'm passing the data instead of the procces of the function. – matibohemio8 Apr 04 '21 at 16:31
  • It's working in this [CodePen](https://codepen.io/Bes7weB/pen/ExZXPxZ?editors=1010) – Louys Patrice Bessette Apr 04 '21 at 17:29

0 Answers0