JulianJ JulianJ - 3 months ago 8
jQuery Question

Getting table id with jquery?

I'm trying to figure out what is wrong with my jquery code. I have some tables on a page and am trying to show the table id in an alert. For reason the alert says the variable is undefined. Can anyone tell me what's wrong?
See my demo here

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

});

});


The Tables

<table id="mytable1">
<tr>
<td class="tags">
<span class="label label-danger" id="tag">Julian</span>
<td class="tags">
<span class="label label-danger" id="tag">Paul</span>
</td>
</tr>
<tr>
<form id="myForm" class="myForm" action="" method="post">
<input type="hidden" name="user_id" value="2">
<button type="submit" name="submit3">
<span class="glyphicon glyphicon-plus-sign"></span> ADD
</button>
</form>
</tr>
</table>


<table id="mytable2">
<tr>
<td class="tags">
<span class="label label-danger" id="tag">John</span>
<td class="tags">
<span class="label label-danger" id="tag">Ben</span>
</td>
</tr>
<tr>
<form id="myForm" class="myForm" action="" method="post">
<input type="hidden" name="user_id" value="2">
<button type="submit" name="submit3">
<span class="glyphicon glyphicon-plus-sign"></span> ADD
</button>
</form>
</tr>
</table>

Answer

The table is not in the form it's present in its ancestor level. Use closest() method to get the table present in the ancestor level.

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

$(document).ready(function() {
  $('.myForm').submit(function(e) {
    var data = $(this).closest('table').attr('id')
    alert(data);
    e.preventDefault();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="mytable1">
  <tr>
    <td class="tags">
      <span class="label label-danger" id="tag">Julian</span>
      <td class="tags">
        <span class="label label-danger" id="tag">Paul</span>
      </td>
  </tr>
  <tr>
    <form id="myForm" class="myForm" action="" method="post">
      <input type="hidden" name="user_id" value="2">
      <button type="submit" name="submit3">
        <span class="glyphicon glyphicon-plus-sign"></span> ADD
      </button>
    </form>
  </tr>
</table>


<table id="mytable2">
  <tr>
    <td class="tags">
      <span class="label label-danger" id="tag">John</span>
      <td class="tags">
        <span class="label label-danger" id="tag">Ben</span>
      </td>
  </tr>
  <tr>
    <form id="myForm" class="myForm" action="" method="post">
      <input type="hidden" name="user_id" value="2">
      <button type="submit" name="submit3">
        <span class="glyphicon glyphicon-plus-sign"></span> ADD
      </button>
    </form>
  </tr>
</table>

Comments