-2

How can I get the id of tbody's input when #moveToAnTable is clicked using jQuery? Thanks.

<table id="yearSectionAdd2Table">
   <thead>
      <tr id="columnHeader">
        <th>
           <div>
               <input id="moveToAnTable" type="button" value="&lt;&lt;">
           </div>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>
          <center>
             <input id="moveToAnTableOne" type="button" value="&lt;&lt;">
          </center>
        </td>
      </tr>
    </tbody>
</table>
scireon
  • 365
  • 2
  • 4
  • 17
  • 12
    This question does not show any research effort. It is important to **do your homework**. Tell us what you found and ***why*** it didn't meet your needs. This demonstrates that you've taken the time to try to help yourself, it saves us from reiterating obvious answers, and most of all it helps you get a more specific and relevant answer. [FAQ](http://stackoverflow.com/questions/how-to-ask). – John Conde May 13 '13 at 14:05
  • @billyonecan They look unique to me, the one in the tbody has "One" on the end. – Anthony Grist May 13 '13 at 14:07
  • @AnthonyGrist right you are, apparently I can't read – billyonecan May 13 '13 at 14:07

2 Answers2

1

Use jQuery.closest to get the table of the button. After that search for the input.

jQuery.attr will return the attribute of the first element in the match:

$("#moveToAnTable").click(function(){
  var id = $(this).closest("table").find("tbody input").attr("id");
  alert(id);
});

See the fiddle:

http://jsfiddle.net/URGVp/

jantimon
  • 36,840
  • 23
  • 122
  • 185
0

You can also write it like this with the on method, and test out your results in a console window if that better suits you, rather than constant pop-ups.

    $('#moveToAnTable').on("click",function(){
      var mvalue = $(this).closest('table').find('tbody input').attr('id');
      console.log('my value is: ' + mvalue);
    });
klewis
  • 7,459
  • 15
  • 58
  • 102