I have run into this problem a few times and I'm not happy with the solutions I've used before.
I have an input box with a blur event that validates the content of it and a button which will fill the input box on click. The problem is clicking the button fires the input blur event and then the button click event so content inserted by the button is not what is validated.
See http://jsfiddle.net/jakecr/dL3K3/
I know this is the correct behavior but I can't think of a clean way to get around the problem.
The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.
It looks like click event has lower priority than blur, so it is predictible behaviour that blur event fires first.
If you want to prevent the blur event from being fired, you have to do so when you are inside the mousedown event, you can do so by invoking the method preventDefault() on the event. Click the checkbox, focus input & then click the button, the textfield never loses focus now.
We had a similar problem at work. what we figured out in the end was that the mousedown event will fire before the blur event allowing you to set the content before the validation or even cancel the validation process completely using a flag.
check this fiddle I made using your example- http://jsfiddle.net/dL3K3/31/
$(function(){ var flag = true; $('input').blur(function(){ if(!$(this).val() && flag){ alert("Grrr, It's empty"); } }); $('button').mousedown(function(){ flag = false; }); $('button').mouseup(function(){ flag = true; $('input').val('content').focus(); }); });
-Edit-
As @mclin Suggested, using the mousedown event and preventDefault will prevent blur behavior. And you can just leave the original click event intact -
http://jsfiddle.net/dL3K3/364/
$(function(){ $('input').blur(function(){ if(!$(this).val()){ alert("Grrr, It's empty"); } }); $('button').mousedown(function(e){ e.preventDefault(); }); $('button').click(function(){ $('input').val('content'); }); });
This solution might be a bit cleaner and better for most cases just note that if you use it you'll preventDefault and blur of any other element the focus is currently on but for most use cases that shouldn't be an issue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With