1
votes

In this HTML

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="x-ua-compatible" content="ie=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <title></title>

    </head>

  <body>

    Enter some number here:
    <input  type="number" min="0" 
          oninput="console.log(' on input '); 
          this.value = Math.abs(this.value);"
          onchange="console.log(' on change');"/>

  </body>
</html>

The input has 2 event handlers

  • input
  • change

However onchange is not called.

Note, the oninput handler changes the value of the input. If I remove

this.value = Math.abs(this.value);

both events are fired.

This behaviour seen in Microsoft Edge 44.17763.1.0 (Microsoft EdgeHTML 18.17763)

This does not happen in Chrome nor in Firefox.

Questions

  1. What am I doing wrong?
  2. Is this from an inherited large code base with many input's all with an oninput and an onchange. The onchange is not called. What is the most efficient way to fix this? (Disclaimer:I'm no HTML / javascript expert.)
1

1 Answers

1
votes

oninput event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus, after the content has been changed.

I try to test your sample code with MS Edge, Chrome and Firefox browser and I am able to produce the issue with MS Edge browser.

Looks like MS Edge browser is working little differently.

I notice that if you try to write the JS code in head part than it can help to solve this issue.

Example:

<!DOCTYPE html>
<html>
<body>
<input  type="number"   onchange="myFunction1(this.value)" oninput="myFunction(this.value)" />
<p id="demo"></p>
<p id="demo1"></p>

<script>
function myFunction(val) {
  document.getElementById("demo").innerHTML = "oninput " + val; 

}
function myFunction1(val) {
  document.getElementById("demo1").innerHTML = "onchange " + val; 
}
</script>

</body>
</html>

Output in MS Edge browser:

enter image description here

User need to press ENTER key or click somewhere else after changing the value to fire the event.