views:

104

answers:

2

Hi all, 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)"
+1  A: 

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();
    }
}
nickf
Thanks, you are right about the `(this)`, but I am a JS noobie and I was just doing it how www.w3schools.com said to do it. Your way helps to clean up the code a bit, but didn't fix my issue. Still, thanks!
typoknig
+1  A: 

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);
desau
I was just getting ready to post back and say that I thought it was doing what you said it was doing (even though I didn't know why) when I read your post. This works very well, but can you explain what `function{el.focus();}` is doing? I would like to understand why this is working.
typoknig
@typoknig - it just calls the focus() function 100 milliseconds later.
nickf
Indeed, as nickf pointed out, it's just delaying the call to focus for 100 milliseconds. This gives your onChange function time to finish (and the subsequent focus change).
desau
Ok, so the word `function` actually calls a function... good to know :)
typoknig
Not exactly. Here we're creating a function declaration. We're essentially creating a function and passing that function declaration (a function "pointer", if you will) to the setTimeout function. window.setTimeout takes 2 arguments. The first being either a function pointer, or a string of script to execute (as eval does).
desau