Javascript : onchange event does not fire when value is changed in onkeyup event [duplicate]

StackOverflow https://stackoverflow.com/questions/15036965

  •  11-03-2022
  •  | 
  •  

Domanda

I have this simply code :

    <body>
        <input type="text" onkeyup="this.value = (new Date()).getSeconds()" onchange="alert(1)" /> 
    </body>

I dont't know why the textbox value has changed when i press the key but the onchange event does not fire. How can i fire onchange event ?

È stato utile?

Soluzione

The onchange will fire when you leave the focus from it (if you performed any changes). This behavior occurs only with text and textarea input types because javascript doesn't know when you're done typing.

I don't know why there is a checkbox in the code, but whatever. Sincerely, I'm not being able to tell you why, but the problem is the dynamic value change on the input (a guess would be that the change isn't performed by the user, but I really don't know), if you remove the code inside the onkeyup it will work. Whatever, if what you want is to execute some code when the input loses focus, you can use onblur instead, is more accurate in that case.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top