Bruno
Bruno

Reputation: 183

Retrieve element with click event from a table

I have a table, where each line has a column with an image and a textarea field where it is to describe the image. how do I click the image to retrieve the textarea content?

$(document).ready(function() {

  $(document).on('click', '.image', function(e) {
    // logic here
   
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
  <tbody>
    <tr>
      <td> <img class="image" src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-512.png" width="100">
      </td>

      <td>
        <textarea class="text"> observation 1 </textarea>
      </td>
    </tr>

    <tr>
      <td> <img class="image" src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-512.png" width="100">
      </td>

      <td>
        <textarea class="text"> observation 2 </textarea>
      </td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Views: 38

Answers (2)

user9263373
user9263373

Reputation: 1074

This solution is presumptive of your current structure showing a two column table with the image in the first column and the textarea in the second column. In essence the solution presumes that since the image is in the first column, it will find the <td> in column 2 containing the <textarea> and get text val() content from that. HTH.

$(document).ready(function() {

  $(document).on('click', '.image', function(e) {
    // logic here
    var text = $(this).closest('td').next('td').find('textarea').val();
    console.log(text);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<table>
  <tbody>
    <tr>
      <td> <img class="image" src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-512.png" width="100">
      </td>

      <td>
        <textarea class="text"> observation 1 </textarea>
      </td>
    </tr>

    <tr>
      <td> <img class="image" src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/female1-512.png" width="100">
      </td>

      <td>
        <textarea class="text"> observation 2 </textarea>
      </td>
    </tr>
  </tbody>

  </table>

Upvotes: 0

Abhishek Mathur
Abhishek Mathur

Reputation: 480

You can use .parent() method followed by .children() method to go up and then go towards the textarea if it is a fixed structure

Upvotes: 1

Related Questions