Search code examples
javascriptdomxhtmldom-events

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>

Solution

  • Since the time you posted the question, I experimented your issue for an hour using different techniques. It now seems to me that through an event on an input, you cannot set focus on itself.

    Still, There is another possible workaround. You can call displayResult() when the form is submitted, check if text1 is empty and cancel submit if it is empty and set focus on text1. I have rewritten the code for you.

    <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").focus();
    return false;
    }
    }
    </script>
    </head>
    <body>
    <form onsubmit="return displayResult();">
    <input type="text" name="text1" id="text1" />
    <input type="text" name="yext2" id="text2" />
    <input type="submit"  />
    </form>
    
    </body>
    </html>
    

    Hope that helps...

    Peace be upon you ...