0

I'm a newbie html and javascript. I have clear code below

HTML

<tr>
    <td>1</td>
    <td>Info1</td>
    <td><input class="btn" value="Show" onclick="showTdSecond();" type="button"></td>
</tr>
<tr>
    <td>2</td>
    <td>Info2</td>
    <td><input class="btn" value="Show" onclick="showTdSecond();" type="button"></td>
</tr>
<tr>
    <td>3</td>
    <td>Info3</td>
    <td><input class="btn" value="Show" onclick="showTdSecond();" type="button"></td>
</tr>

Javascript

<script type="text/javascript">
function showTdSecond() {

}

I want click a button I will get a text value of second. Example : Info1, Info2, Info3. Please help me,

1
  • Thanks, but your way is not automatical, i choose an answer of "Rajaprabhu Aravindasamy" Commented May 11, 2016 at 7:16

2 Answers 2

4

First of all you have to pass the this value to the inline event handler,

<input class="btn" value="Show" onclick="showTdSecond(this);" type="button">

Then use the this context and traverse to the relevant element and collect its text,

function showTdSecond(_this) {
 alert(_this.parentNode.previousElementSibling.textContent);
}

Here you can read more about previousElementSibling.

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

You can put runnable snippets in your answer so no need for a link to another site.
0

You can use the cellIndex property of the cell with the parent row to get the previous cell:

function showTdSecond(el) {
  var cell = el.parentNode;
  alert(cell.parentNode.cells[cell.cellIndex - 1].textContent);
}
<table>
  <tr>
    <td>1</td>
    <td>Info1</td>
    <td><input class="btn" value="Show" onclick="showTdSecond(this);" type="button"></td>
  </tr>
  <tr>
    <td>2</td>
    <td>Info2</td>
    <td><input class="btn" value="Show" onclick="showTdSecond(this);" type="button"></td>
  </tr>
  <tr>
    <td>3</td>
    <td>Info3</td>
    <td><input class="btn" value="Show" onclick="showTdSecond(this);" type="button"></td>
  </tr>
</table>

1 Comment

Good answer ! Give me more knowledge :) Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.