Reputation:
My code for getting the id of the tr in a table is not working.
I retrieved the data of the table from mysql db and populated the table. But for the better and easy to read, let's just assume I have this table here:
<table>
<tr id = "1" class = "tablerow">
<td> Your awesome </td>
</tr>
<tr id = "2" class = "tablerow">
<td> Your great </td>
</tr>
<tr id = "3" class = "tablerow">
<td> Your amazing </td>
</tr>
</table>
and also have this js:
$(".tablerow").click(function(event){
var id = this.id;
alert(id);
});
but it's not working, it just alert's an empty string. Why?
Upvotes: 3
Views: 636
Reputation: 183
you should use:
$(".tablerow").click(function(e) {
var proxy = this.id;
id = this.id;
console.log(id);
});
Upvotes: 1
Reputation: 2349
You should use
$(".tablerow").click(function(event){
var id = $(this).attr('id');
alert(id);
});
Explaination
When you are trying to access this
inside the click event you are only accessing the element but you want to select that DOM Element, so you should use
$(this) //it will select the DOM element as a Jquery object.
Then you should use attr method of Jquery to access attributes of the particular DOM Element.
Upvotes: 1
Reputation: 2197
Assuming you have only one table on your page:
document.getElementsByTagName("tr")[index].id;
Preferably though, you'd give your table a id, though, and get your row like this:
<table id="tableId">
<tr id = "1" class = "tablerow">
<td> Your awesome </td>
</tr>
<tr id = "2" class = "tablerow">
<td> Your great </td>
</tr>
<tr id = "3" class = "tablerow">
<td> Your amazing </td>
</tr>
</table>
js code:
var table = document.getElementById("tableId");
var row = table.rows[index];
console.log(row.id);
Upvotes: 1
Reputation: 2378
try to change your code to next
$(".tablerow").click(function(event){
var clicked = $(this),
id;
if(clicked.attr('id')){
id = clicked.attr('id');
}
else{
id = clicked.parent().attr('id');
}
alert(id);
});
Upvotes: 1
Reputation: 1082
Try this code, hope it may help you:
$(document).on("click",".tablerow",function(event){
var id = this.id;
alert(id);
});
If it still not working try to check also if your jquery is declared. like this one: <script src="../js/jquery-1.11.1.min.js"></script>
Enjoy!
Upvotes: 0