Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Javascript focus() method work in onBlur event for input text box?

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>
like image 949
Tasneem Fathima Avatar asked Mar 27 '12 06:03

Tasneem Fathima


1 Answers

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);
    }
}
like image 75
Andy E Avatar answered Sep 18 '22 12:09

Andy E