Reputation: 29518
I'm parsing XML and putting it in a simple table like this:
function showData(message) {
var str = "<table border=1 class='editable'>";
for (var i = 0; i < message.length; i++) {
str += "<tr>" + "<td>" + message[i].id + "</td>" +
"<td>" + message[i].name + "</td>" +
"<td>" + message[i].url + "</td>" +
"<td>" + message[i].desc + "</td>" +
"<td>" + "<a href='javascript:deleteRequest();' id=message[i].id>delete</a>" + "</td>" + "</tr>";
}
str += "</table>";
return str;
}
I have an tag in the last column of my table and I'm trying to set the id of the tag, or be able to get it from my deleteRequest method so I can delete that entry in the table.
1) I'm not sure if I'm setting the id correctly for the tag.
2) I'm not sure how to get the id in my deleteRequest method for the selected tag, like a sender in iOS, or maybe to pass the id in as an argument to deleteRequest(). I'm not sure which method is better. I tried to do a simple alert(arguments[0]) to see what gets passed in this case, and I get undefined. So I'm kind of lost what to do as I'm just learning Javascript. Thanks.
Upvotes: 0
Views: 271
Reputation: 150080
Try something like this for the line with the link in it:
"<td>" + "<a href='javascript:deleteRequest(this);' id='" + message[i].id + "'>delete</a>" + "</td>" + "</tr>";
// OR, without the extra + operations:
"<td><a href='javascript:deleteRequest(this);' id='" + message[i].id + "'>delete</a></td></tr>";
You weren't concatenating the value from message[i].id
into the string you are producing, you were including the string "message[i].id". (Note that that line ends up looking similar to the four lines of code before it.)
If you pass this
as a parameter to your function, like deleteRequest(this)
as shown above you can do this:
function deleteRequest(el) {
// el is the <a> that was clicked
alert(el.id); // displays the id from the row that was clicked
}
(Obviously the alert(el.id)
is just an example of how to access the id
property, you'll do whatever you want with it at that point.)
Note about terminology: Your question title was "Get id element of an tag" - id
is an attribute, the link is an anchor element (or "a" element), and in your html markup the anchor element is defined with an <a>
tag. (Similarly, "href" is an attribute.)
EDIT: I just noticed you have your JS embedded within the href
attribute. I'm not sure if that will work properly with the this
keyword, but in any case a better way to do it is:
<a href="#" onclick="deleteRequest(this); return false;">
Or, within your code:
"<td><a href='#' onclick='javascript:deleteRequest(this);return false;' id='" + message[i].id + "'>delete</a></td></tr>";
Upvotes: 2