Reputation: 485
I am using jQuery and my goal is to get the id of next table. I will simplify the code here:
The simplified HTML looks like this:
<div>
<img src="png.png" class="exportIcon" alt='' onClick="tableExport()">
<table class="table tablesorter" id="tableHourlyT"><tr><td></td></tr></table>
</div>
And I then have the following function:
<script>
function tableExport(){
tableID = $(this).next('table').attr("id");
alert(tableID);
}
</script>
But the alert says "undefined" and in fact I cant even do anything with the table, I tried hiding it etc. It just doesn't find it. I also tried replacing the next()
with closest()
but I still had the same result. What I need to do is always when the function is called, get the id of the closest following table from that element (clicked image/button).
Upvotes: 0
Views: 472
Reputation: 1
Also use:
var tableID = $(element).next('table').attr("id");
instead:
tableID = $(element).next('table').attr("id");
Variable without var prefix will be defined in global scope
Upvotes: 0
Reputation: 1714
You shouldn't use the onClick attribute, but rather use a jQuery event handler:
$(".exportIcon").click(tableExport); //bind tableExport as the handler whenever an export icon is clicked function tableExport() { ... }When you bind the event that way, you'll find that $(this) is correctly set to the element that was clicked.
http://www.codeply.com/go/y6OAZFRZSn
(I replaced your img with a button for the demo, but it would work the same.)
Upvotes: 0
Reputation: 13816
Here's one way to do what you want - pass the element as an argument to the tableExport function:
<div>
<img src="png.png" class="exportIcon" alt='' onClick="tableExport(this)">
<table class="table tablesorter" id="tableHourlyT"><tr><td></td></tr></table>
</div>
Then, use that in a jQuery selector:
<script>
function tableExport(element){
tableID = $(element).next('table').attr("id");
alert(tableID);
}
</script>
Upvotes: 3