Sumit Sinha
Sumit Sinha

Reputation: 666

Select a child td of a tr by id in a table

I have a table from which, through jQuery, I want to select the text of firstname from the tr whose button was pressed.

A tr row look like :

....
<tr id = "2">
    <td>
        <input type="checkbox">
    </td>
    <td id = "firstname">
        John
    </td>
    <td id = "lastname">
         Doe
    </td>
    <td>
            <button id = "2" class="button">change</button>
    </td>
</tr>
....

That button above is linked to a jQuery :

$(".button").click(function(){
    var element = $(this);
    var id = element.attr("id");
    var newusername = $("tr#"+id+" > td#firstname").html();
    alert(newusername);
});

Why doesn't my selector work?

Upvotes: 1

Views: 5850

Answers (2)

rfornal
rfornal

Reputation: 5122

Since IDs must be unique, try ...

<tr id = "2">
  <td>
    <input type="checkbox">
  </td>
  <td class = "firstname">
    John
  </td>
  <td class = "lastname">
     Doe
  </td>
  <td>
     <button data-id = "2" class="button">change</button>
  </td>
</tr>

... and ...

$(".button").click(function(){
  var element = $(this);
  var id = element.data("id");
  var newusername = $("#" + id + " > .firstname").html();
  alert(newusername);
});

Changing the name IDs to classes and changing the selection should work. Also, only one ID of 2. I used data-id on the button so that I can still select what the value is and didn't duplicate the id.

NOTE:

The data- "data dash" attribute is an attribute that I used here to allow for quicker capture of the attribute; jQuery has a .data() function that specifically looks for these types of attributes.

.data() link

Upvotes: 3

Ga&#235;l Barbin
Ga&#235;l Barbin

Reputation: 3929

It seems that you have several element with the same id. In that case, the correct usage is to use a class:

<td class="firstname">
...
<td class = "lastname">

Then your selector becomes: $("tr#"+id+" > td.firstname")

Upvotes: 0

Related Questions