JulianJ
JulianJ

Reputation: 1317

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>

Upvotes: 0

Views: 325

Answers (2)

Drew Kennedy
Drew Kennedy

Reputation: 4168

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.

Upvotes: 1

Colin
Colin

Reputation: 361

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.

Upvotes: 2

Related Questions