Javascript Problem Set focus textbox on Firefox
Posted by in Javascript March 2, 2012 2 Comments

I have in situation like this. I have two text boxes, when I focus on first textbox for input something, If I want to leave this textbox to move to second textbox , I have to input some value in it. I try to use getElementById and focus() event to set focus on the first textbox in case I does not input any value in it. It works fine on IE, Google Chrome but it doesn’t work Firefox.

+ HTML example :

Text 1 : <input id="Text1" onblur="SetFocus()" type="text" value="" />
Text 2 : <input id="Text2" type="text" value="4rapiddev.com" />

+ Use getElementById and focus() to set focus on “Text 1″ incase user does not input data:

<script type="text/javascript" language="javascript">// 
function SetFocus() {
    var ctrl = document.getElementById("Text1");
    if (ctrl != null && ctrl.value == '') {
        ctrl.focus();
    }
}
</script>

The ctrl.focus() above doesn’t work on Firefox but when I try with setTimeout(Add some delay in focusing of the field), it works fine :)

<script type="text/javascript" language="javascript">
// Working both IE and Firefox
function SetFocus {
    var ctrl = document.getElementById("Text1");
    if (ctrl != null && ctrl.value == '') {
        setTimeout(function() { ctrl.focus(); }, 1);                
    }
}              
</script>

Hope it is helpful for someone! :)

  • nilesh shinde

    How to make it work in Safari browser on iPad..

  • Rowell

    You, my friend, are a Godsend! Thank you.