0

I have a simple piece of HTML like this, stored in hr.html

<html>

<head>
    <title>Heart rate</title>
</head>

<body>
    <form>
        <label for="age">Age: </label>
        <input type="text" id="age" name="age"><br><br>
        <label for="restHR">Resting HR: </label>
        <input type="text" id="restHR" name="restHR"><br><br>

        <input type="submit" value="Submit" onclick="printResult()">
    </form>
    <div id='output'></div>
    <script>
        const calTargetHR = (age, restHR) => {
            let targetHR = (((220 - age) - restHR)) + restHR;
            return targetHR
        }
        const printResult = () => {
            document.getElementById("output").innerHTML = calTargetHR(
                document.getElementById('age').value,
                document.getElementById('restHR').value
            )
        }
    </script>
</body>

</html>

I run it by just double click the file. In the address bar it shows as:

file:///C:/Users/work/hr.html?age=&restHR=

The problem is, if I input some value and press the submit button, it's not showing the result because the path becomes:

file:///C:/Users/c21127478/CM6612%20Web/topic3/work/hr.html?age=3&restHR=4

How do I solve this?

one-hand-octopus
  • 2,229
  • 1
  • 17
  • 51

1 Answers1

2

You can add return false to the end of the onClick statement. This prevents the default HTML5 behavior of a form: W3C The button element

<input type="submit" value="Submit" onclick="printResult();return false">
breezertwo
  • 585
  • 7
  • 26
  • Thank you, although this answers my question. https://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – one-hand-octopus Oct 14 '21 at 18:26