I have several divs
that each contain a form
. Each of the forms has two input text
fields
.
I am trying to trigger
a function
after div looses focus
(meaning, not after one of the input text fields looses focus, but after totally new form in new div gains focus).
<div class='userInput' id='userInputID'>
<div class='col1'>
<form id='form1' method='post' action='BuyOrder.php'>
<input type='text' name='r1' id='r1' value=''><br />
<input type='text' name='b1' id='b1' value=''><br />
<button id='button1' class='sendButton'>send</button>
</form>
</div>
<div class='colX'>
<form id='formX' method='post' action='BuyOrder.php'>
<input type='text' name='rX' id='rX' value=''><br />
<input type='text' name='bX' id='bX' value=''><br />
<button id='buttonX' class='sendButton'>send</button>
</form>
</div>
<div class='col2'>
<form id='form2' method='post' action='BuyOrder.php'>
<input type='text' name='r2' id='r2' value=''><br />
<input type='text' name='b2' id='b2' value=''><br />
<button id='button2' class='sendButton'>send</button>
</form>
</div>
</div>
And here is jquery code:
$('#userInputID').children().blur(function(){
//some code
})//end blur
Basically, I want the function to run when any of the divs with the class col1, colx or col2 looses focus. The jquery code above never even fires. Focusout doesn't work because that fires after each input text fields loose focus, even if the same div still has focus.
How to fire a function after div has lost focus (blur)
Based on tests and on these pages 1, 2 it seems that blur does not bubble. But you can use a workaround. This updated fiddle shows that it works according to my understanding of your question:
id='userInputID'
If you use the jQuery function
on()
you can capture focus and blur events.And the html
Fully working demo at fiddle with update dec 2013
As Chris Rockwell pointed out my former fiddle demo does not work if the tab key is used. I created a fork that works with the tab key as well
And simplified HTML
Please let me know if you have further questions.
Some quotes
From the jQuery Api on blur
The
.blur()
documentation would lead you to believe that you can use it this way; however, I believe you must explicitly trigger the blur on an element that is not a valid form element (e.g. input, select, etc.);See this fiddle: http://jsfiddle.net/z7VYQ/
Based on your comment regarding validation, this fiddle shows you how to determine the currently focused form, and make adjustments to the other forms.