Problem with "on change" followed by "on click"

1

I have the following HTML code:

<input type="text" id="esc" />
<input type="button" value="Ok" id="ok" />

And jquery / javascript:

$(document).on("change", "#esc", function(){
    alert("esc");
});

$(document).on("click", "#ok", function(){
    alert("ok");
});

When I type text in a textbox and click directly on Ok, it does not execute the code inside the click function. Only the change function code.

Follow exemeplo on fiddle: link

What is the reason for this and how can I resolve this "conflict"?

    
asked by anonymous 29.09.2015 / 16:53

1 answer

5

Joao,

What happens is as follows.

When you change the text, it releases the textbox change trigger and tries to click the button. The event is triggered before the click and the alert is called, then canceling your click event.

If you change the code to the next.

$(document).on("change", "#esc", function(){
    console.log("esc");
});

$(document).on("click", "#ok", function(){
    console.log("ok");
});

You will see that the two events are fired normally. The problem with your example is alert, which becomes preemptive and prevents you from triggering the button's click event because it "passes in front".

Did you understand?

To explain it better. Is your button event the right click? It is fired when the user clicks the button. But in your text input it triggers the change event as soon as you exit the text input, and in milliseconds (viewable to us humans) it triggers the change event and within the change event it calls the alert BEFORE < you have successfully clicked the button. And when the alert was called "canceled" your click, why could not you actually click the Ok button.

    
29.09.2015 / 17:04