开发者

Copy cell value from table to textbox

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>


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜