user2195741
user2195741

Reputation:

How get the second td innerHTML

Scenario:

I'm using datatable library to display alot of information. That table have the following rows:

Id   Type     Name      Case

What I'm looking for is that when I click the second row Type, that value will be taking and pasted in a textbox

Example

Id   Type     Name      Case
1    text     Juan       20001
3    List     Pedro      20005

If I click the row that has the id # 1, I need to take the Type innerHTML. Does not matter what apart of the row I click just take the second td's html.

I tried with this code:

$("tr td").click(function () {

    alert($(this).html());
    })

It worked great, But the problem is that the user have to click exactly the row Name, but would be better if user can click over any of the row and just take the second rows html.

Suggesstions?

Upvotes: 2

Views: 5226

Answers (3)

Adil
Adil

Reputation: 148150

Try using eq()

but would be better if user can click over any of the row and just take the second rows html.

$("tr td").click(function () {
    secondrow = $(this).closest('tr').siblings().eq(1);
});

If i click the row that has the id # 1, i need to take the Type innerHTML. Does not matter what apart of the row i click just take the second td's html.

$("tr td").click(function () {
    secondTd = $(this).siblings().eq(1);
    alert(secondTd.html());
});

Upvotes: 1

Ejaz
Ejaz

Reputation: 8872

Try this

     $(function () {
        $("#thetable tr").click(function () {
           if ($(this).index() == 0) return;
           $('#tbox').val($('td:nth-child(2)', $(this)).html())
        })
     });

HTML

  <table border="1" cellpadding="4" id="thetable">
     <tr>
        <td>Id</td>
        <td>Type</td>
        <td>Three</td>
        <td>Four</td>
     </tr>
     <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
     </tr>
     <tr>
        <td>5</td>
        <td>6</td>
        <td>7</td>
        <td>8</td>
     </tr>
  </table><br />
  <input type="text" name="tbox" id="tbox" />

It method takes into account the first row that contains only labels and doesn't set the textbox value to a label if top row is clicked.

Upvotes: 0

Mike Samuel
Mike Samuel

Reputation: 120546

myRow.getElementsByClassName('td')[1].innerHTML

should get you the innerHTML of the second table cell of myRow as long as the first table cell does not contain a nested table.

You might try adding the click handler to the rows instead of to the cells too.

Upvotes: 2

Related Questions