最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

JavaScript will not pass focus to element - Stack Overflow

programmeradmin0浏览0评论

I have the following function in JavaScript every part of the if statement executes properly except giving focus back to the element which called the function. It does not work in IE or Fire Fox, and neither browser gives me an error. It looks correct to me... Why isn't it working?

function check(x){

     //doing some stuff

     if (uc_check == false){
          window.alert('Houston, we have a problem.');
          document.getElementById(x).value = '';
          document.getElementById(x).focus(); //this line is not working 
     }
}

P.S. I am calling this function from a form input like this:

onchange="check(this.id)"

I have the following function in JavaScript every part of the if statement executes properly except giving focus back to the element which called the function. It does not work in IE or Fire Fox, and neither browser gives me an error. It looks correct to me... Why isn't it working?

function check(x){

     //doing some stuff

     if (uc_check == false){
          window.alert('Houston, we have a problem.');
          document.getElementById(x).value = '';
          document.getElementById(x).focus(); //this line is not working 
     }
}

P.S. I am calling this function from a form input like this:

onchange="check(this.id)"
Share Improve this question asked Jun 22, 2010 at 5:06 ubiquibaconubiquibacon 10.7k30 gold badges116 silver badges187 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 7

The problem here is that when the onChange function finishes, it sets focus to the next element. So, any focus you set in that function will only go away after the onChange ends.

You can get around this a number of ways. Probably the easiest is to use a timeout.

Change your focus line to the following:

var el = document.getElementById(x);
window.setTimeout(function(){el.focus();}, 100);

You already have a reference to the element (this) so you don't need to pass an id around:

<input onchange="check(this);">

And the JS:

function check(el) {
    if (uc_check == false) {
        el.value = '';
        el.focus();
    }
}
发布评论

评论列表(0)

  1. 暂无评论