0

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>
JulianJ
  • 1,259
  • 3
  • 22
  • 52
  • Possible duplicate of [Form onSubmit determine which submit button was pressed](http://stackoverflow.com/questions/3577469/form-onsubmit-determine-which-submit-button-was-pressed) – Itay Aug 14 '16 at 13:49
  • Having classes the same as id's and the same name on multiple elements really makes things more convoluted than it needs to be. – Drew Kennedy Aug 14 '16 at 13:50

2 Answers2

2

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.

Colin
  • 351
  • 6
  • 16
1

If the table element is always immediately within the form, you can use the children function. One benefit to it is it should work faster as it only traverses through elements immediately within the parent and doesn't traverse through all levels of HTML.

$(function() {
  $('.myForm').submit(function(e) {
      e.preventDefault();

      var table = $(this).children('table').attr("id");

      //do something with table
  });
});

Otherwise, find as Colin suggested would definitely be the best option.

Drew Kennedy
  • 4,118
  • 4
  • 24
  • 34
  • Just out of (bad?) habit, I never use 'children' but just use .find('> table') if I want to specify an immediate descendant. There's an interesting thread over here on the speed difference: http://stackoverflow.com/questions/648004/what-is-fastest-children-or-find-in-jquery If the top answer there is correct it may be faster to use find() in this case. – Colin Aug 14 '16 at 14:34