Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript will not pass focus to element

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)"
like image 756
ubiquibacon Avatar asked Apr 10 '26 01:04

ubiquibacon


1 Answers

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);
like image 67
desau Avatar answered Apr 12 '26 15:04

desau