How to make Javascript focus() method work in onBlur event for input text box?
It's not possible to reapply focus to an element when its blur event triggers. Use a timer with an interval value of 0
to delay the call to focus until afterwards:
function displayResult() {
var inp1 = document.getElementById("text1").value,
inp2 = inp1.length;
if(inp2==0) {
alert("Field 1 cannot be left Empty");
//document.getElementById("text1").value="";
window.setTimeout(function () {
document.getElementById("text1").focus();
}, 0);
}
}
You need to set little delay in the focusing of the field.
setTimeout(function(){field.focus()}, 10);
like :
<html>
<head>
<script type="text/javascript">
function displayResult(obj)
{
var inp1=obj.value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
setTimeout(function(){obj.focus()}, 10);
}
}
</script>
</head>
<body>
<form>
<input type="text" name="text1" id="text1" onblur="displayResult(this);"/>
<input type="text" name="yext2" id="text2" />
<input type="submit">
</form>
</body>
</html>
I advise you not to use onblur in validating inputs if you are display notification message as alerts. It's quite annoying , it produces endless alerts . Validate form onsubmit event.