JulianJ JulianJ - 3 months ago 11
jQuery Question

How to select element of particular table?

I have a page made up of multiple tables with unique id's each containing a form.
How can I get the id of the table where the submit button was clicked?
I eventually want to use the id as a selector to display data in.
See my demo

The Jquery

$(document).ready(function() {
$('.myForm').submit(function(e) {
var data = $('table').attr('id');
alert(data);

e.preventDefault();

});

});


The html

<form id="myForm" class="myForm" action="" method="post">
<table id="mytable1">
<tbody>
<tr>
<td>
my table 1
</td>
</tr>
</tbody>
</table>
<button type="submit" name="submit3">Submit

</button>
</form>
<form id="myForm" class="myForm" action="" method="post">
<table id="mytable2">
<tbody>
<tr>
<td>
my table 2

</td>
</tr>
</tbody>
</table>
<button type="submit" name="submit3">Submit

</button>
</form>

Answer

This should do it:

var data = $(this).find('table').attr('id')

(Ha. Get it? this should do it? I'm a laugh riot.)

this is going to give you the form that was submitted, so finding the table within it should get you want you want.