For me Javascript focus() method is working fine if I use it with a button and onClick event, but with onBlur from a text box, it is not working. Can anyone guide me on this?
<html>
<head>
<script type="text/javascript">
function displayResult()
{
var inp1=document.getElementById("text1").value;
var inp2=inp1.length;
if(inp2==0)
{
alert("Field 1 cannot be left Empty");
//document.getElementById("text1").value="";
document.getElementById("text1").focus();
}
}
</script>
</head>
<body>
<input type="text" name="text1" id="text1" onBlur="displayResult();"/>
<input type="text" name="yext2" id="text2" />
</body>
</html>
                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);
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With