0

following function should write a value on my html page:

function f(){
var aa;
aa = document.getElementById("a");
document.getElementById('resultarea').innerHTML += aa;
}

It works, but the value appears only for a few milliseconds. Then the value is gone. What is the problem? Why do my page a reset?

html code:

   <div>
  <form>
     <label for="a">a:</label>
     <input type="number" name="a" id="a" />
     <button onclick="f()">Calculate</button>

  </form>
</div>
<div id="resultarea"></div>
Hias
  • 45
  • 6

1 Answers1

2

The default action for a button in a form is to submit the form (which triggers a POST request, essentially reloading the page in this case).

You need to add type="button" to the button to prevent this behavior, or .preventDefault() on the event.

function f() {
  var aa;
  aa = document.getElementById("a");
  document.getElementById('resultarea').innerHTML += aa.value;
}
<div>
  <form>
    <label for="a">a:</label>
    <input type="number" name="a" id="a" />
    <button onclick="f()" type="button">Calculate</button>
  </form>
</div>
<div id="resultarea"></div>
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
  • that was it - many thanks! I searched hours and doesn't found it... – Hias Nov 11 '22 at 06:26
  • @Hias Most of this is documented in the MDN guide: [Sending form data](//developer.mozilla.org/en/docs/Learn/Forms/Sending_and_retrieving_form_data) and [Client-side form validation](//developer.mozilla.org/en/docs/Learn/Forms/Form_validation). Also, Inline event handlers like `onclick` are [bad practice](/q/11737873/4642212). They’re an [obsolete, cumbersome, and unintuitive](/a/43459991/4642212) way to listen for events. Always [use `addEventListener`](//developer.mozilla.org/en/docs/Learn/JavaScript/Building_blocks/Events#inline_event_handlers_%E2%80%94_dont_use_these) instead. – Sebastian Simon Nov 11 '22 at 07:21