Beware of this
. It is a crazy variable and you always, always want to think twice before adding it in your code.
Before we debug, the first lesson is -
- Every function is always called in a context and if you can't tell the context, it is the
window
object.
Now let's breakdown what's going on here.
When a user presses a key on your input field, insertComment
is called. Since there is no context, it is called on the window context. So now, inside the function, your this
is actually pointing to window
, and there's no window.attr('id')
defined.
It is equivalent to calling window.insertComment
where this == window
.
If you modify your code like so -
onkeydown='if (event.keyCode == 13) insertComment(this)'
function insertComment(x){
alert(x.attributes.id);
}
Here, the context will still be window
, i.e this
variable will still point to window
object, but the input
element itself will be passed as a parameter to the insertComment
function.
x
will refer to the element and you can now pull the id
attribute in good old fashioned javascript way - x.attributes.id
(or in jQuery way, if you prefer - $(x).attr('id')
)