[javascript] document.getElementById(id).focus() is not working for firefox or chrome

When ever I do onchange event, its going inside that function its validating, But focus is not comming I am using document.getElementById('controlid').focus();

I am using Mozilla Firefox and Google Chrome, in both its not working. I don't want any IE. Can any one tell me what could me the reason.

Thanks in advance

Here's the code:

var mnumber = document.getElementById('mobileno').value; 
if(mnumber.length >=10) {
    alert("Mobile Number Should be in 10 digits only"); 
    document.getElementById('mobileno').value = ""; 
    document.getElementById('mobileno').focus(); 
    return false; 
}

This question is related to javascript

The answer is


Not all elements are focusable but default, there is a tabindex attribute to fix that.

When you assign tabindex= to an element:

It becomes focusable. A user can use the tab key to move from the element with lesser positive tabindex to the next one. The exception is a special value tabindex="0" means that the element will always be last. The tabindex=-1 means that an element becomes focusable, but the tab key will always skip it. Only the focus() method will work


The timeout suggested above worked around the issue on Chrome. No issue exists on IE8 or FF3.

My code that to set focus that worked is:

window.setTimeout(function() {
  document.form1.password.focus();
}, 0);

I suspect the reason this works is the browser rendering runs on the same thread as javascript, and setTimeout(function(){},0); queues the javascript function inside setTimeout to execute when the browser becomes idle. If anyone has a more in-depth explanation please share it.

setTimeout(function(){ 
 if(document.getElementById('mobileno')){
  document.getElementById('mobileno').focus();
 } 
},0);

Your focus is working before return false; ,After that is not working. You try this solution. Control after return false;

Put code in function:

function  validateNumber(){
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        return false; 
    }else{
        return true;
    }
}

Caller function:

function submitButton(){
        if(!validateNumber()){
            document.getElementById('mobileno').focus();
            return false;
        }
}

HTML:

Input:<input type="text" id="mobileno">
<button onclick="submitButton();" >Submit</button>

One thing to check that I just found is that it won't work if there are multiple elements with the same ID. It doesn't error if you try to do this, it just fails silently


One more thing to add to this list to check:

Make sure the element you are trying to focus is not itself nor is contained in an element with "display: none" at the time you are trying to focus it.


For getting back focus to retype password text box in javascript:

window.setTimeout(function() { document.forms["reg"]["retypepwd"].focus(); },0);

Here, reg is the registration form name.


Try location.href='#yourId'

Like this:

<button onclick="javascript:location.href='#yourId'">Show</button>

Place this source above your modal :

<script>
$('body').on('shown.bs.modal', '#IdYourModal', function () {
    document.getElementById('mobileno').focus();
})
</script>

2 things to mention if focus() not working:

  • use this function after appending to parent
  • if console is selected, after refreshing page, element will not gain focus, so select (click on) the webpage while testing

This way works in both Firefox and Chrome without any setTimeOut().


Are you trying to reference the element before the DOM has finished loading?

Your code should go in body load (or another function that should execute when the DOM has loaded, such as $(document).ready() in jQuery)

body.onload = function() { 
    // your onchange event handler should be in here too   
    var mnumber = document.getElementById('mobileno').value; 
    if(mnumber.length >=10) {
        alert("Mobile Number Should be in 10 digits only"); 
        document.getElementById('mobileno').value = ""; 
        document.getElementById('mobileno').focus(); 
        return false; 
    }    
}

Add a control, where you want to set focus then change its property like below

<asp:TextBox ID="txtDummy" runat="server" Text="" Width="2" ReadOnly="true" BorderStyle="None" BackColor="Transparent"></asp:TextBox>

In the codebehind, just call like below txtDummy.Focus()

this method is working in all browser.


I know this may be an esoteric use-case but I struggled with getting an input to take focus when using Angular 2 framework. Calling focus() simply did not work not matter what I did.

Ultimately I realized angular was suppressing it because I had not set an [(ngModel)] on the input. Setting one solved it. Hope it helps someone.


window.setTimeout(function () { 
    document.getElementById('mobileno').focus(); 
}, 0); 

This worked for me also. Firefox would set the value of my element, but not give focus to it.


My case was a bit different. I was trying to focus() an input from within a browser developer console. Turns out it was interfering with the input somehow, and once I minimized the console everything worked as expected. I understand this isn't a programmatical solution, but in case someone found this on a search engine jist like I did, there's a chance this information might help.


Make sure you use "id" and "getElementById" as shown here:

<FORM id="my_form" name="my_form" action="">
<INPUT TYPE="text" NAME="somefield" ID="somefield" onChange="document.getElementById('my_form').submit();">
</FORM>

Try using a timer:

var mnumber = document.getElementById('mobileno').value;
if (mnumber.length >=10) 
{ 
    alert("Mobile Number Should be in 10 digits only");
    document.getElementById('mobileno').value = "";
    window.setTimeout(function ()
    {
        document.getElementById('mobileno').focus();
    }, 0);
    return false;
}

A timer with a count of 0 will run when the thread becomes idle. If that doesn't help, try the code (with the timer) in the onblur event instead.