TheRealPapa
TheRealPapa

Reputation: 4539

Access contents of div inside table cell

I have a JSFiddle here.

I am trying to access the text content of the div with class '.item_description' for all rows in a table where a checkbox has been checked, but I cannot seem to get it.The checkbox is in a nested table in each row.

My HTML is:

<table id="table-tasks-list" class="table-hover">
  <tbody>
    <tr id="row-task-10572" class="task-modal-row">
      <td >
        <div class="task_description pull-left" style="padding:5px 0 0 5px;">Qui at dolore sit alias cum voluptate ad...</div>
        <table class="pull-right" style="border:none;">
          <tbody>
            <tr>
              <td style="width:80px;border:none;">2015-02-23</td>
              <td class="hours" style="width:30px;border: none;">8.00</td>
              <td class="row-icon tasks-check-box" style="border: none;">
                <label class="checkbox-hold">
                  <input type="checkbox" name="bill-task" id="chk-10572" class="task-checkbox ion-fw" checked=""><span class="fake-input checkbox-icon ion-android-checkbox-outline-blank ion-fw" data-chk-id="10572"></span></label>
              </td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr id="row-task-10573" class="task-modal-row">
    ....

In my JS, I do:

$('table#table-tasks-list tbody tr td input.task-checkbox').each(function(i, check) {       
  if ($(check).is(':checked')) {
    console.log($(check).closest('table#table-tasks-list tbody tr').find('.task_description').text());
 }     
});

But i get empty results. What have i missed? Thanks!

Upvotes: 1

Views: 512

Answers (4)

woshilapin
woshilapin

Reputation: 269

I don't have an answer about why it doesn't work. However, I believe I reached similar problem and fixed it by using $(this) inside the loop instead of using the second argument of the callback function (check in your example). I hope this helps...

Upvotes: 0

james_bond
james_bond

Reputation: 6906

Use

$(check).closest(".task-modal-row").find(".task_description").text();

To access the content of the closest .task_description

Upvotes: 3

Lio
Lio

Reputation: 1503

According to your code it should be like this:

$(check).closest('.task-modal-row').find('.task_description').text()

Demo : https://jsfiddle.net/TheRealPapa/sw5Lh6pa/1/

Upvotes: 2

tao
tao

Reputation: 90208

Your closest() targets the whole table and outputs the contents of all .task-description it finds, regardless of checkboxes. You only need to go up to the containing tr:

console.log($(check).closest('tr[id^="row-task-"]').find('.task_description').text());

Upvotes: 1

Related Questions