0

so I'm working on a school project. The goal is to calculate the surface of a triangle in javascript and display the results in html. I created a form to enter the values of the variables g and h.

Now I want to replace the header text with getelementbyid but somehow it pops up and disappears directly when I click the button. try it yourself and let me know what I'm doing wrong.

function berechnen() {
  var g = document.getElementById("grundfläche").value;
  var h = document.getElementById("höhe").value;

  var fläche = g*h/2;
  var ergebnis =  "Das Ergebnis für die Flächenberechnung eines Dreickecks mit der Grundfläche " + g + " und der Höhe " + h + " beträgt " + fläche;
  document.getElementById('heading').innerText = ergebnis;

}
<!DOCTYPE html>
<html lang="de" dir="ltr">

<head>
  <meta charset="utf-8">
  <title>Fläche eines Dreiecks</title>
  <link rel="stylesheet" type="text/css" href="style.css">
  <script src="rechnung.js" charset="utf-8"></script>
</head>

<body>

  <div class="container">
    <h1 id="heading">Die Fläche eines Rechtecks berechnen</h1>
    <form>
      <input type="text" name="grundfläche" id="grundfläche" maxlength="10" placeholder="Gib die Grundseite des Dreiecks ein">
      <input type="text" name="höhe" id="höhe" maxlength="10" placeholder="Gib die Höhe des Dreiecks ein">

      <button type="submit" onclick="berechnen()">Berechnen</button>
    </form>
  </div>
</body>

</html>

2 Answers2

1

So, you have the onclick on a submit button, which submits the form.

You see the change from your javascript, but then your form is posted to the server, refreshing the page, and the change is gone.

So add return false to the javascript method:

function berechnen() {
//...existing code 
    return false; 
}

and it should behave as you expect (i.e. without submitting the form)

Alternatively change the type=submit to button

Berechnen

MemeDeveloper
  • 6,457
  • 2
  • 42
  • 58
0

Try to change your button type to

submit

if you don't have any intention to submit and modify any data on the server side:

<button type="button" onclick="berechnen()">Berechnen</button>
Willy David Jr
  • 8,604
  • 6
  • 46
  • 57