-1

I have a table that has its rows generated by variables in my software and I want the rows to highlight when they are clicked. Here is my code:

$("#varTable > tbody:last").append("<tr style='border: 1px dotted black;'  onclick=\"rowClick('" + newVariable.Name + "','" + this + "')\">><td><img id='Img12' src='images/Delete.png' width='35' height='35' style='margin-left:0px; margin-top: 10px;'></td><td>New Variable</td><td>Global</td><td></td><td><center>0</center></td><td><form action=''>" +
    "<center><input type='checkbox' name='RetainValue' value='Retain'></center></form></td><td width='100px'><button type='button' onclick='editVariable()'>Edit</button></td></tr>"); 

}

function rowClick(name, row){
console.log(row);
selectVariable = name; 
$("#selName").html("Selected Variable: <font color='red'>" + selectVariable + "</font> Filter By: <button type='button' onclick='addVariable()'>Add Variable</button>");
$(row).css("border", "1px solid black");

}

My issue is when I pass "this" into the function rowClick it comes up as [window object] and not the tr that the onclick is located in. I also tried using this.element but that said it was undefined. Thanks for any help I can get.

Joe
  • 15,205
  • 8
  • 49
  • 56
  • 4
    Since you're already using jQuery you could just remove the onClick from your markup and do a $('body').on('click', 'tr', function(){... and have the new variable assigned to a data attribute. Just a thought. – Jay Blanchard May 15 '14 at 19:02
  • 1
    @JayBlanchard That's exactly what I was thinking. – user1477388 May 15 '14 at 19:06

2 Answers2

3

You need to pass this as part of the string

$("#varTable > tbody:last").append("<tr style='border: 1px dotted black;'  onclick=\"rowClick('" + newVariable.Name + "',this)\">><td><img id='Img12' src='images/Delete.png' width='35' height='35' style='margin-left:0px; margin-top: 10px;'></td><td>New Variable</td><td>Global</td><td></td><td><center>0</center></td><td><form action=''>" +
    "<center><input type='checkbox' name='RetainValue' value='Retain'></center></form></td><td width='100px'><button type='button' onclick='editVariable()'>Edit</button></td></tr>"); 

You need to evaluate this at the time of the event. Currently, you're evaluating it at the time of the append.

Smeegs
  • 9,151
  • 5
  • 42
  • 78
0

Change:

 rowClick('" + newVariable.Name + "','" + this + "')

to this:

 rowClick('" + newVariable.Name + "',this)
T McKeown
  • 12,971
  • 1
  • 25
  • 32