Wednesday, July 23, 2008

focusing in on a field that's empty with javascript

There seems to be a weirdness when leaving a field that's empty and trying to get the browser to focus back on it. It does it momentarily, but then decides to go back. This script will force the cursor back and focus on the offending field after .1 seconds of leaving it.


<script>
var myInput = '';
function checkMe(obj) {
if(obj.value == '') {
myInput = obj;
myInput.style.background = 'yellow';
myInput.setAttribute('title','This is a required field and blah blah blah');
window.setTimeout('myInput.focus()',100);
}
}
</script>
<input id="foo1" name="foo1" value="init" onchange="checkMe(this);">

<input id="foo2" name="foo2" value="check" onchange="checkMe(this);">

<input id="foo3" name="foo3" value="last" onchange="checkMe(this);">

No comments: