1

I am trying to pass an element through my function and output the id.

Here is what I mean:

<input id='password' style="display:inline-block" type="password" name='Password' onKeyDown="setTimeout('validate(this)', 10)" />

and the javascript:

var validate = function(element)
{
    alert(element.id);        
}

Is this the correct way to do the following? All I get is undefined when it alerts. Thank you.

1

1 Answer 1

4

When called from the setTimeout function, the this pointer is no longer pointing to the input element, rather it is pointing to the window object.

What you can do is

onKeyDown="var self=this;setTimeout(function(){validate(self);}, 10)"

Or better yet:

var validateFn = function(element) {
    return function(){
        alert(element.id);
    };
}

and on the element:

onKeyDown="setTimeout(validateFn(this), 10)"
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect! Ha, I thought I was going crazy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.