简体   繁体   中英

Catch cell value specifies an HTML table with jquery

I need to get the contents of <tr> containing his first <td> equal to "4" in the third an textbox. In this case appear the number "2099451" in the textbox.

  <table id="tableHtml">
    <tr>
        <td>rank</td>
        <td>place</td>
        <td>population</td>
        <td>lat</td>
        <td>lo</td>
    </tr>
    <tr>
        <td>1</td>
        <td>New York city</td>
        <td>8175133</td>
        <td>40.71455</td>
        <td>-74.00712</td>
    </tr>
    <tr>
        <td>2</td>
        <td>Los Angeles city</td>
        <td>3792621</td>
        <td>34.05349</td>
        <td>-118.24532</td>
    </tr>
    <tr>
        <td>3</td>
        <td>Chicago city</td>
        <td>2695598</td>
        <td>45.37399</td>
        <td>-92.88875</td>
    </tr>
    <tr>
        <td>4</td>
        <td>Houston city</td>
        <td>2099451</td>
        <td>41.337462</td>
        <td>-75.73362</td>
    </tr>
    <tr>
        <td>5</td>
        <td>Philadelphia city</td>
        <td>1526006</td>
        <td>37.15477</td>
        <td>-94.48611</td>
    </tr>
    <tr>
        <td>6</td>
        <td>Phoenix city</td>
        <td>1445632</td>
        <td>32.46764</td>
        <td>-85.00082</td>
    </tr>
    <tr>
        <td>7</td>
        <td>San Antonio city</td>
        <td>1327407</td>
        <td>37.706576</td>
        <td>-122.44061</td>
    </tr>
    <tr>
        <td>8</td>
        <td>San Diego city</td>
        <td>1307402</td>
        <td>37.707815</td>
        <td>-122.46662</td>
    </tr>
    <tr>
        <td>9</td>
        <td>Dallas city</td>
        <td>1197816</td>
        <td>40.636</td>
        <td>-91.16830</td>
    </tr>
    <tr>
        <td>10</td>
        <td>San Jose city</td>
        <td>945942</td>
        <td>41.209716</td>
        <td>-112.00304</td>
    </tr>

</table>

I'm trying to do this with the following code:

var table = $('#tableHtml');

var value = $(table).find('tr').filter(function(){ 
    return $(this).children('td').eq(2).text() == 4;
});

$('#GetValue').val(value);

Code in JSFidlle

Thanks!

You could do:

$('#GetValue').val($('#tableHtml td:nth-child(1):contains("4")').next().next().text());

jsFiddle example

Another option is:

var value = $('#tableHtml td:nth-child(1)').filter(function () {
    return $(this).text() === '4';
}).next().next().text()
$('#GetValue').val(value);

jsFiddle example

var table = $('#tableHtml');

var value = $(table).find("tr").eq(4).find("td").eq(2).text();

$('#GetValue').val(value);

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