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 ?

hieund
  • 356
  • 1
  • 6
  • 16
  • use oninput for everything exept ie – zb' Feb 23 '13 at 04:18
  • Use: `onkeyup="this.value = (new Date()).getSeconds();this.onchange();"` – Ian Feb 23 '13 at 04:34
  • @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. – hieund Feb 23 '13 at 06:47

1 Answers1

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.

martriay
  • 5,632
  • 3
  • 29
  • 39
  • explanation to the downvotes? I would like a correction with that, if not I'll stay wrong. – martriay Feb 23 '13 at 04:36
  • "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) – hieund Feb 23 '13 at 06:42
  • 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. – martriay Feb 23 '13 at 07:28
  • 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. – hieund Feb 23 '13 at 07:37
  • Ok copying my comment into the answer to be more visible to someone with the same doubt. – martriay Feb 23 '13 at 07:38
  • 1
    `onblur` was a help. :) – Nirav Zaveri Aug 21 '13 at 12:42