简体   繁体   中英

jQuery How to get td cell value

I am trying to get the value of invoice number when user clicks anywhere on a row

Below is my table

<div class="panel ui-widget-content" id="invoiceList">
<h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; "><span>Invoices</span></h2>
    <table cellspacing='0' id='header' class="ui-widget">
        <tr>
            <th>Invoice Number</th>
             <th>Invoice Total</th>
        </tr>     
        <tr>
            <td><a href="#"  >INV-Error_Test1</a></td>
            <td>22.000000 USD</td>
        </tr>
        <tr>
            <td><a href="#"  >INV-Error_Test2</a></td>
           <td>22.000000 USD</td>
        </tr>
    </table> 
</div>

Below is the jQuery I have which gives the Invoice Number only if its clicked on Invoice Number field

$("#invoiceList td").click(function (e) {
var result = $(this).text();
console.log('invoice --->'+result);
});

http://jsfiddle.net/5n62md3m/

Can someone help me get the invoice number when user clicks anywhere on the row.

Check this, it could be a solution:

 $('tbody tr').on('click', function(e){ var value = $(this).find('td:first-child a').text(); alert(value); e.stopPropagation(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <div class="panel ui-widget-content" id="invoiceList"> <h2 class="ui-widget-header ui-corner-top" style="cursor: pointer; "><span>Invoices</span></h2> <table cellspacing='0' id='header' class="ui-widget"> <thead> <tr> <th>Invoice Number</th> <th>Invoice Total</th> </tr> </thead> <tbody> <tr> <td><a href="#" >INV-Error_Test1</a></td> <td>22.000000 USD</td> </tr> <tr> <td><a href="#" >INV-Error_Test2</a></td> <td>22.000000 USD</td> </tr> </tbody> </table> </div> 

$("#invoiceList tr:not(:first-child)").click(function (e) {
    console.log('invoice ---> '+$(this).children('td:nth-child(1) a').text());
}

A small bonus here that if you want to get another column, you can only change the number in nth-child (and remove the trailing a , possibly).

Another alternative solution could be

$('#invoiceList tr:not(:first-child)').click(function(e){
   $tds = $(this).find("td");
   console.log( $tds.eq(0).text());
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM