-2

Hello everyone and sorry for my english.

Following this jdfiddle, I have a problem I don't understand.

First I change the value of the input, then I click on the button and what I expected to see is "click" but I see "change" meaning onclick is called after onchange.

<input type="text" onChange="alert('change')" />
<button type="button" onClick="alert('click');">Click!</button>

I found on this post that it's because of chrome which fires onchange event before the onclick event. But I don't really have the same need as this post because my event are not declared in the same tag. And secondly, if I click on the button I would like to only execute the onclick function and not onclick and then onchange (this methods consists in using onMouseDown).

Do you have a good method to do that?

Community
  • 1
  • 1
Clemzd
  • 895
  • 2
  • 15
  • 35
  • In your case onchange event will definitely be called before onclick event because Change event is executed because the focus will be out of text box when you click the button. – Vivek Gupta Mar 25 '15 at 11:22
  • this is working as intended, you have focus on a changed element when you press the button, to that event will fire first. As I understand your question you should just remove the onchagen event?? – Henrik Mar 25 '15 at 11:25
  • @Henrik What if I want to keep the code in onchange event? – Clemzd Mar 25 '15 at 12:38
  • Why would you? - onChange detects when the field no longer has focus you should really not rely on that. it is better to look for the OnKeyUp or similar event.. – Henrik Mar 25 '15 at 13:14

1 Answers1

0

Ok so I can see that you really wan't this. You could let the on change function run first, and then afterward see what has focus, if it is that button, you would know that it was clicked, and thus was the reason for loosing focus.

you cannot check this while the change function is running, as the body still has focus at this time..

<head>
  <script language="javascript">
  function focussed()
  {
    var triggerElement = document.activeElement
    alert(triggerElement)
    console.info(triggerElement)
  }

  function change()
  {
    alert("change")
    setTimeout(focussed, 1)
    return true
  }
  </script>

</head>
<body>
    <input type="text" onChange="alert('change')" />
    <button type="button" onClick="alert('click');">Click!</button>
</body>
Henrik
  • 2,180
  • 16
  • 29