Danielle Rose Mabunga
Danielle Rose Mabunga

Reputation: 1724

Get the value of class in TD JQuery click

I want to get the current value from a class from a td in table

script

 $(".edit").click(function() {
        // $("#cost").modal();
        id = $('tr').find('td.cost').text();
        alert(id);
    });

table

 foreach($val as $val)
<tr>
  <td class="cost">{{ $val->cost}}</td>
  <td>{{$val->value }} </td>
  <td><a class="edit"></a></td>

endforeach

I tried

 $(".edit").click(function() {
        // $("#cost").modal();
        id = $('tr').find('td.cost').text();
        alert(id);
    });

but it will get all values like 12,23,23 (assuming there are three ids fetch from db)

Upvotes: 2

Views: 2317

Answers (4)

Sunny S.M
Sunny S.M

Reputation: 5988

Use this code : Example : HTML

<table>
  <tr>
    <td class="cost">12</td>
    <td>hello</td>
    <td><a class="edit">edit</a></td>
  </tr>
   <tr>
    <td class="cost">15</td>
    <td>hi </td>
    <td><a class="edit">edit</a></td>
  </tr>
   <tr>
    <td class="cost">20</td>
    <td>hey</td>
    <td><a class="edit">edit</a></td>
  </tr>
</table>

JS

$(".edit").click(function() {
  var id = $(this).closest('tr').find('td.cost').text();
  alert(id);
});

Jsfiddle example

Upvotes: 0

madalinivascu
madalinivascu

Reputation: 32354

Use siblings

$(".edit").click(function() {
        // $("#cost").modal();
        id = $(this).siblings('td.cost').text();
        alert(id);
    });

Demo https://jsfiddle.net/w6ea9hnn/

Upvotes: 0

SM3RKY
SM3RKY

Reputation: 1597

Have your function defined in javascript and call it from the HTML using an onclick event, rather than binding it from your javascript file.

eg

foreach($val as $val) 
    <tr>
        <td class="cost">{{ $val->cost}}</td>  
        <td>{{$val->value }} </td>   
        <td>
            <a class="edit" onclick="myFunction(this)"></a>
        </td>
    </tr>

and then in javacript define a function like the following

function myFunction(item) {
    var text = $(item).text();
}

Upvotes: 1

Anik Islam Abhi
Anik Islam Abhi

Reputation: 25352

Try like this

id = $(this).closest('tr').find('td.cost').text();

DEMO

Upvotes: 1

Related Questions