GetElementById (id) . focus()不适用于 Firefox 或 chrome

每当我做一个变化事件,它的内部函数的验证,但焦点是不来我使用 document.getElementById('controlid').focus();

我正在使用 MozillaFirefox 和 GoogleChrome,它们都不能正常工作。我不想要 IE。谁能告诉我为什么。

先谢谢你

密码是这样的:

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;
}
203566 次浏览

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.

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>

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

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.

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.

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.

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

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

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>

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.

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.

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

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.

Place this source above your modal :

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

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>

I also faced this type of problem in vue js.

I fixed this problem using vue $nextTick method Vue 2

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

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