Get table value with jQuery

0

I would like to get the value of a column from the table, but in a way that I could reuse the function to get values from other tables.

I tried the following, but it does not show me anything on the console.

NOTE: The value for the line only.

HTML

<table class="table">
    <thead></thead>
    <tbody class="table-hover">
        <tr>
          <td id="id">2</td><td>Cliente N - 1</td>
          <td>teste</td>
          <td>2017-02-14 22:00:52</td>
          <td class="txt-center pointer"><span class="glyphicon glyphicon-ok txt-error pointer" onclick="updateStatus()"></span></td>
        </tr>
        <tr>
          <td id="id">3</td>
          <td>Cliente N - 2</td>
          <td>teste</td>
          <td>2017-02-14 22:00:52</td>
          <td class="txt-center pointer"><span class="glyphicon glyphicon-ok txt-error pointer" onclick="updateStatus()"></span></td>
        </tr>
    </tbody>
  <tfoot></tfoot>

jQuery

function updateStatus(param){ //param seria o numero da coluna
  var teste  = $('table > tbody').closest('tr').find('td').eq(param).text();
  console.log(teste);
}

then through the param I would indicate the column to get the value ...

    
asked by anonymous 23.02.2017 / 01:11

1 answer

1

First, add a parameter to the function that will reference the span where you are calling the function. I called the obj parameter. In the call, add the value this to this parameter. In the second parameter, param , pass the number of the column you want to fetch. In the example below, I used 1, then search for the values in the first column, 2 and 3, depending on the line.

To access the value through jQuery, we look for the tag tr where span is:

$(obj).parents("tr")

Next, we look for the nth tag % with_data, where the value of td is defined by the value of n :

$(obj).parents("tr").find("td:nth-child(" + param + ")");

With this, we can call the function param to get the value of the column:

console.log(column.html());

See below working:

function updateStatus(obj, param) {
  var column = $(obj).parents("tr").find("td:nth-child(" + param + ")");
  console.log(column.html());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><tableclass="table" border="1">
  <thead></thead>
  <tbody class="table-hover">
    <tr>
      <td id="id">2</td>
      <td>Cliente N - 1</td>
      <td>teste</td>
      <td>2017-02-14 22:00:52</td>
      <td class="txt-center pointer">
        <span class="glyphicon glyphicon-ok txt-error pointer" onclick="updateStatus(this, 1)">
          Icon
        </span>
      </td>
    </tr>
    <tr>
      <td id="id">3</td>
      <td>Cliente N - 2</td>
      <td>teste</td>
      <td>2017-02-14 22:00:52</td>
      <td class="txt-center pointer">
        <span class="glyphicon glyphicon-ok txt-error pointer" onclick="updateStatus(this, 1)">
          Icon
        </span>
      </td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>
    
23.02.2017 / 02:15