1

How can I search for the column random ID in the table, I can only search for the values in the unique ID column. What seems to be the error?

Sample Code:

<table>
        <tr><th>Unique ID</th><th>Random ID</th></tr>
        <tr><td>214215</td><td>442</td></tr>
        <tr><td>1252512</td><td>556</td></tr>
        <tr><td>2114</td><td>4666</td></tr>
        <tr><td>3245466</td><td>334</td></tr>
        <tr><td>24111</td><td>54364</td></tr>
    </table>
    <br />
    <input type="text" id="search" placeholder="  live search"></input>


$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});

2 Answers 2

1

You need to use :nth-child(2) instead of :first to get the second td and not the first one:

more info here

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:nth-child(2)").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

Use nth-child property.

$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:nth-child(2)").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
        <tr><th>Unique ID</th><th>Random ID</th></tr>
        <tr><td>214215</td><td>442</td></tr>
        <tr><td>1252512</td><td>556</td></tr>
        <tr><td>2114</td><td>4666</td></tr>
        <tr><td>3245466</td><td>334</td></tr>
        <tr><td>24111</td><td>54364</td></tr>
    </table>
    <br />
    <input type="text" id="search" placeholder="  live search"></input>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.