Here is a demo (jsfiddle) with a forms and two fields:
<div id="container">
<form>
<div class="field">
<input id="demo" type="text" name="demo" />
</div>
<div class="field">
<input id="demo2" type="text" name="demo2" />
</div>
</form>
</div>
The code looks like this:
$(document).ready(function() {
$('#container').click(function(evt) {
if(this == evt.target) {
console.log('clicked container',evt.target);
$('#demo').focus();
} else {
console.log('clicked child -> ignoring');
}
});
$('.field').click(function(evt) {
if(this == evt.target) {
console.log('clicked field div',evt.target);
$(this).find('input').focus();
} else {
console.log('clicked child -> ignoring');
}
});
});
You can click the container that contains the form to set the focus on the first input field or behind the input field to set the focus into it.
If you click into the field, then the click will be ignored.
The code above works since jQuery assigns the DOM node to this
before calling event handlers, so you can easily check whether the current event was published by the DOM node by checking
this == evt.target
CSS:
#container {
width: 600px;
height: 600px;
background: blue;
}
.field {
background: green;
}