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

1

7

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 ?

Bullyboy answered 23/2, 2013 at 4:9 Comment(3)
use oninput for everything exept ieWongawonga
Use: onkeyup="this.value = (new Date()).getSeconds();this.onchange();"Aeromarine
@Barmar, Ian : I don't need the onchange event happen right after the value of textbox change in onkeyup function. I need the alert(1) show when I click to the page to leave the textbox.Bullyboy
J
1

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.

Juniper answered 23/2, 2013 at 4:14 Comment(6)
explanation to the downvotes? I would like a correction with that, if not I'll stay wrong.Juniper
"why would you do that ?" : Because I have to get the input value when keyup, if it is not valid, I will correct it and return the valid value. After I change the input value, i will do something else in onchange event. But, in this SIMPLE code, the onchange does not fire even when i click to the page to leave focus the textbox. (you can copy it into notepad, save as html to check)Bullyboy
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.Juniper
Yes, the checkbox is needn't, i removed it from the code. I cannot understand too. By the way, the onblue event satify my need. Thank you very much.Bullyboy
Ok copying my comment into the answer to be more visible to someone with the same doubt.Juniper
onblur was a help. :)Erickericka

© 2022 - 2024 — McMap. All rights reserved.