Having this sample code:
<input type="text" id="changeid">
<a href="#" id="clickb">click</a>
<script>
$('#clickb').on("click", function(event){
alert(1);
return false;
});
$('#changeid').on("change", function(event){
alert(2);
return false;
});
</script>
When putting something into the text field and click the link immediately, only onchange event fires, but not link click event. Why is that? It seems that the change event is blocking the click event?
Having this sample code:
<input type="text" id="changeid">
<a href="#" id="clickb">click</a>
<script>
$('#clickb').on("click", function(event){
alert(1);
return false;
});
$('#changeid').on("change", function(event){
alert(2);
return false;
});
</script>
When putting something into the text field and click the link immediately, only onchange event fires, but not link click event. Why is that? It seems that the change event is blocking the click event?
Share Improve this question edited Sep 14, 2012 at 2:06 xdazz 161k38 gold badges253 silver badges278 bronze badges asked Sep 13, 2012 at 10:13 abikuabiku 2,2465 gold badges25 silver badges31 bronze badges4 Answers
Reset to default 11It is blocked by alert
. Change alert
to console.log
you will find two events all fired.
The demo.
$('#clickb').on("click", function(event){
console.log(1);
return false;
});
$('#changeid').on("change", function(event){
console.log(2);
return false;
});
When you edit the input and then click on the link the following happens on the inside
- You start clicking on the 'link'. No events are generated yet (not even mousedown), because first the browser will do some cleanup work:
- The input loses focus and will raise a
blur
event - The input raises a
change
event, since it raised ablur
and the value changed - Your
change
event callback opens analert(2)
- The documents loses focus since a new window appeared
- The link will never experience the
click
.
The solution is not to use alert
(as xdazz proposed).
use this
$("#changeid").live('change', function () ...
onchange event fires only after the element is blurred. So when u type some text and click on the link first the element is blurred on the text field. The best way to handle the change event on having onkeyup event to track the changes made on the text field.