views:

33

answers:

2

I have the following table. I want to copy Id value on the seleced row to the text box. If I click on link "Select" in the first row the text box value will 0001.

If the table needs modification to get result better and faster, please leave your suggestion.

<div>
    <input id="selectedId" type="text" />
  </div>

  <table cellspacing="1" class="tablesorter" id="nameList">
    <thead>
      <tr>
        <th class="header">Name</th>

        <th class="header">Id</th>

        <th class="header">Gender</th>

        <th>Select</th>
      </tr>
    </thead>

    <tbody>
      <tr>
        <td>Akom Smith</td>

        <td>0001</td>

        <td>M</td>

        <td><a href="#" class="click-to-select">Select</a></td>
      </tr>

      <tr>
        <td>Amara Sahara</td>

        <td>0002</td>

        <td>F</td>

        <td><a href="#" class="click-to-select">Select</a></td>
      </tr>

      <tr>
        <td>John Lache</td>

        <td>0003</td>

        <td>M</td>

        <td><a href="#" class="click-to-select">Select</a></td>
      </tr>
    </tbody>
  </table>
+3  A: 

try this,

$('a.click-to-select').click(function() {
    var id = $(this).closest('tr').find('td').eq(1).text();
    $('#selectedId').val(id);
    return false;
});​

simple cool demo

added notes for the comment below.

$('a.click-to-select').click(function() {
    var id = $(this).closest('tr').find('td.id').text();
    $('#selectedId').val(id);
    return false;
});​

updated demo

Reigel
I like the cool demo. Thank you. If have a class 'td' like this <td class="id">0001</td>, how would the syntax be?
Narazana
see added notes ;)
Reigel
A: 

Well, you know your key is the second td in the row. You can use the :nth-child selector like this:

<script type="text/javascript">
var getUniqueId = function() {
     return $('td:nth-child(2)').text();
}
</script>

Of course you need a way to identify the correct , but I assume the code is supposed to be called from each and there you can use the parent selector.

Otherwise I'd put an id attribute in each row to make selecting easier.

thomasmalt