Alerting the this.id keyword returns undefined Javascript

user2342875 picture user2342875 · Oct 10, 2013 · Viewed 12.9k times · Source

I create the same inputbox a couple of times dynamically. When a user presses enter it calls a function. I then test with this code:

function insertComment(){
  alert($(this).attr('id'));
}

But it keeps returning undefined. Here is the syntax I use to create similiar input boxes:

$("#divToAppend").append("<input id='testID' type = 'text' class = 'formatCSS' style = 'margin-top:12px ; ' placeholder = 'Add Comment' onkeydown='if (event.keyCode == 13) insertComment()'></input>");

Answer

Vicky Gonsalves picture Vicky Gonsalves · Oct 10, 2013

Just pass this while calling method :

$("#divToAppend").append("<input id='testID' type = 'text' class = 'formatCSS' style = 'margin-top:12px ; ' placeholder = 'Add Comment' onkeydown='if (event.keyCode == 13) insertComment(this)'></input>");


function insertComment(this)
{ 
alert($(this).attr('id')); 
}