I want to do input validation with jQuery. Every time the user blurs an input, it should get validated. The validation is not the problem, it’s the focus part.
Some inputs are embedded in a bigger parent element. The parent element should be the indicator for focusin and focusout events. In other words: If the user clicks on the parent element of the input, it should focus the input.
Here is a demonstration:
DEMO on jsFiddle
In the demo, the first input is surrounded by a ul which is clickable and causes the underlying input to focus. The second input is surrounded by a div which does nothing. Watch the console for the output.
Here is the markup taken from the demo. HTML:
<ul>
<li>
<input type="text" class="embed" />
</li>
</ul>
<div>
<input type="text" class="normal" />
</div>
JavaScript:
$('input').focusin(function(event) {
console.log('input.' + $(this).attr('class') + ' focusin');
});
$('input').focusout(function(event) {
console.log('input.' + $(this).attr('class') + ' focusout');
// either here or in blur:
// now i want to do some validation and display errors if there are any
});
$('input').blur(function(event) {
console.log('input.' + $(this).attr('class') + ' blur');
// either here or in focusout:
// now i want to do some validation and display errors if there are any
});
$('ul').click(function(event){
console.log('ul click');
$('input.embed').focus();
});
Currently these are my questions and problems:
- When clicking on the embedded
input, it also fires theulclick event, which i do not want. How can i detect in that event if the input was clicked directly? - If the embedded
inputis already focused, and i click on the parentul, it fires the focusout event of theinput(which would trigger the validation) and immediately focuses it again because of theulclick handler. How can detect this and simply do nothing? Because in fact, from the point of view of the user, the focus didn’t change. - What’s the difference between
blurandfocusout?
For your first question:
For your third question, from
jQueryapi documentation: