manraj82
manraj82

Reputation: 6295

what does this.id return?

function test(){
alert(this);//alerts oblect
alert(this.id);//alerts undefined

}

<input type="text" onKeyPress="test();" id="text1">

why does alert(this.id) alert undefined? Is this because this returns the document object?

Thank You

Upvotes: 2

Views: 4460

Answers (3)

Zimbabao
Zimbabao

Reputation: 8240

In global scope the context (this) is windows, since window have no property called "id" its undefined.

Upvotes: 0

KV Prajapati
KV Prajapati

Reputation: 94625

Your code should be.

function test(objRef){
  alert(objRef);//alerts oblect
  alert(objRef.id);//alerts undefined
}

<input type="text" onKeyPress="test(this);" id="txtNum" />

EDIT: You may use following code too.

<script type="text/javascript">
        window.onload = function() {
            var txtnum = document.getElementById("txtNum");
            txtnum.onkeypress = function() {
                alert(this);
                alert(this.id);
            };
        };
 </script>

 <input type="text" id="txtNum" />

Upvotes: 3

Andreas Dolk
Andreas Dolk

Reputation: 114757

this is the window instance. Try it in your browser:

javascript:alert(this)

I get an [object Window]

Upvotes: 2

Related Questions