Kaker
Kaker

Reputation: 645

Undefined when retrieving text from element

I have this code

<tr><td id="name">TEXT 1</td> 
<td><input type="button" class="button_add" value="Add" ></td></tr>
<tr><td id="name">TEXT 2</td> 
<td><input type="button" class="button_add" value="Add" ></td></tr>

I would to click on the button to read the value of the current element td. For eg.: "This is your text: TEXT1"-

My code in jQuery is :

$('.button_add').click(function() {
    var name = $(this).attr("#name").html();
    alert('This is your text' + name);
});

But when I click on the button I get the following error:

TypeError: $(...).attr(...) is undefined

And it doesn't work. What am I missing?

Upvotes: 2

Views: 882

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

ID of an element must be unique, so use name as a class instead of as ID.

Since you need the value of td in the same tr, use .closest to find the tr then use the class selector to find the td

$('.button_add').click(function() {
  var name = $(this).closest("tr").find('td.name').html();
  //or since the target td is the previous sibling of the button's parent element
  //  var name = $(this).parent().prev().html();

  alert('This is your text' + name);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="name">TEXT 1</td>
    <td>
      <input type="button" class="button_add" value="Add">
    </td>
  </tr>
  <tr>
    <td class="name">TEXT 2</td>
    <td>
      <input type="button" class="button_add" value="Add">
    </td>
  </tr>
</table>

Upvotes: 3

Related Questions