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; 
}

Try using a timer:

const id = "mobileno";
const element = document.getElementById(id);
if (element.value.length >= 10) {
    alert("Mobile Number Should be in 10 digits only");
    element.value = "";
    window.setTimeout(() => element.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.


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().


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.