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

Viewed 199540

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

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.

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.

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.

I also faced this type of problem in vue js.

I fixed this problem using vue $nextTick method

this.$nextTick(() => {                      
    this.$refs['ref-name'].focus(); 
});

you can use it inside of vue js mounted lifecycle hooks.

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

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>

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

Try location.href='#yourId'

Like this:

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