onchange function does not work after reset the form

Viewed 17

I have the following html and JS:

<body>
    <form id="form_test">
        <label>Your name: </label>
        <input type="text" name="name">
        <label>Your age: </label>
        <input type="number" name="age" onchange="update()" value="0" min="0">
        <button type="button" onclick="send(this.form)">Send</button>
    </form>

    <script>
        function send(forma){
            let data = Object.fromEntries((new FormData(forma)).entries());
            console.log(data);
            forma.reset();
        }
        function update(){
            console.log('Input number has changed');
        }
    </script>
</body>

When I fill the form an send it with an age different of 1 I can go back and fill the form again, as you can see in the code, there is a console log for every time I change the age, however, If I send the form with an age of 1, and then I fill the form again, but changing the age with the input number buttons, it looks like the onchage event does not work, but if I change the value by typing everything works fine. Do you know why this is happening? As I mentioned, this only happens after sending the form with the input number equals to 1 and by changing the value with the input number buttons.

1 Answers

Prefer to code this "natural" way:

const formTest = document.querySelector('#form_test') // same as CSS notation

formTest.onsubmit = evt =>
  {
  evt.preventDefault(); // disable form submit / page reload

  let data = Object.fromEntries((new FormData(formTest)).entries());
  console.clear();
  console.log(data);
  formTest.reset();
  }
formTest.age.onchange = evt => // use form's elements names directly
  {
  console.clear();
  console.log('Input number has changed :', formTest.age.valueAsNumber );
  }
<form id="form_test">
  <label>Your name: </label>
  <input type="text" name="name">
  <br>  <br>
  <label>Your age: </label>
  <input type="number" name="age" value="0" min="0">
  <br>
  <br>
  <button type="submit">Send</button>
</form>

Related