Robert Ross
Robert Ross

Reputation: 1189

Getting a value from table with jQuery

I am trying to get a value from my table cells using jQuery. I am new to jQuery and I tried many things, but nothing gave me the sought result. Below are some examples of what I've tried so far. I simply want to get the text between the <td></td> tags.

The DOM looks like this : enter image description here

I tried with :

$("tr td:nth-child(3)").text();

Which got me :

none111none222none111none222

I also tried with :

$(this).closest('#idDom').text()

But this resulted in nothing.

Any input will be appreciated.

Upvotes: 0

Views: 84

Answers (3)

Robert Ross
Robert Ross

Reputation: 1189

The following code worked for me. (i changed the id's to classes as suggested above)

$(this).closest("tr").find(".nameDom").text()

Upvotes: 0

You have 2 elements "tr" and you need to specify:

alert($("tr:nth-child(1) td:nth-child(3)").text());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tbAtendidos">
  <thead>
    <tr>
      <th>Year</th>
      <th>Month</th>
      <th>Name</th>
    </tr>
  </thead>   
  <tbody>
    <tr>
      <td>1981</td>
      <td>05</td>
      <td>Marc</td>
    </tr>
    <tr>
      <td>1982</td>
      <td>06</td>
      <td>Michael</td>
    </tr>
  </tbody>
</table>

Upvotes: 0

Pedro Estrada
Pedro Estrada

Reputation: 2419

$("tr td:nth-child(3)").text();

This gets you every 3rd td in every tr, thats why you're getting all that text appended.


After you convert all the columns id to class.. You can do something like this:

$('#lblEditDeleteProducts .priceDom').eq(0).text()

Using the image in your question, this would return 123


To explain the selector:

$('#lblEditDeleteProducts .priceDom') this will return an array of all the elements with class of priceDom inside the element with id lblEditDeleteProducts.

.eq(0) this will return the first element in the array from above

.text() this will return the text of the element above

Upvotes: 1

Related Questions