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
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
Share Improve this question asked Feb 18, 2011 at 12:02 manraj82manraj82 6,34525 gold badges58 silver badges85 bronze badges3 Answers
Reset to default 3Your 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" />
this
is the window instance. Try it in your browser:
javascript:alert(this)
I get an [object Window]
In global scope the context (this) is windows, since window have no property called "id" its undefined.