0

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).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Jachym
  • 485
  • 9
  • 21
  • 2
    That's because `this` has no meaning inside your function. You will have to start by using a jquery selector _somewhere_. For example, use `$('table')` to let jQuery select all tables, then request the id of sed table. – somethinghere Sep 24 '15 at 16:18
  • 1
    possible duplicate of [How can I get the ID of an element using jQuery?](http://stackoverflow.com/questions/3239598/how-can-i-get-the-id-of-an-element-using-jquery) – Adam Buchanan Smith Sep 24 '15 at 16:20
  • You don't need event handlers on every image: this should be enough for all images/tables (IF same HTML structure is repeated): http://jsfiddle.net/cu2z29mh/1/ – sinisake Sep 24 '15 at 16:25

3 Answers3

3

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>
HaukurHaf
  • 13,522
  • 5
  • 44
  • 59
0

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.)

Carl Bussema
  • 1,684
  • 2
  • 17
  • 35
0

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

Mike
  • 1