firstStep firstStep - 1 month ago 8
HTML Question

Enable partial match search for a column of html table

I have a html table populated on screen. I have written a piece of working code to filter the table using a comma separated string on a column. For e.g - Column Name = ID,
The example filter string that I gave = 1,2,3,4,6,8,9,90. So it displays only the rows with these ID`s. My JS code is as follows-

$(function () {

$("#filter").click(function () {
try {
ids = $("#inputFilter").val();
if (ids != "") {
idsArray = ids.split(",");
$("#my-table tr:gt(0)").hide();
$.each(idsArray, function (i, v) {
$("#my-table tr[data-id=" + v + "]").show();
})
} else {
$("#my-table tr").show();
}
}
catch (error) {
try {
$body.removeClass("loading");
}
catch (error) {
}
alert(error);
}
});
});


Now I want to enable partial search for ID`s, that means, for e.g as I type 23,45,78,4324,5436,321321 the table should start filtering for partial matches too. How can this be implemented?

Answer

First, you need to remove extra spaces then split(",") and JQuery selector [attribute*=”value”] would be like $("#my-table tr[data-id*='" + v + "']") witch select all rows with data-id' value has any of search input IDs, try this example:

$(function () {

    $("#filter").click(function () {
        try {
            ids = $("#inputFilter").val();
            if (ids != "") {
                idsArray = ids.replace(/[\n\r\t]/g,"").replace(/\s+/g,"").split(",");
                $("#my-table tr:gt(0)").hide();

            $.each(idsArray, function (i, v) {
             $("#my-table tr[data-id*='" + v + "']").show();
                })
            } else {
                $("#my-table tr").show();
            }
        }
        catch (error) {
            try {
                $body.removeClass("loading");
            }
            catch (error) {
            }
            alert(error);
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='inputFilter'>
<button id='filter'>filter</button>

<table id='my-table'>
<tr><th>ID</th><th>Name</th></tr>
<tr data-id="1"><td>1</td><td>Tom 1</td></tr>
<tr data-id="2"><td>2</td><td>John 1</td></tr>
<tr data-id="3"><td>3</td><td>Van 1</td></tr>
<tr data-id="10"><td>10</td><td>Tom 10</td></tr>
<tr data-id="20"><td>20</td><td>John 20</td></tr>
<tr data-id="30"><td>30</td><td>Van 30</td></tr>
<tr data-id="101"><td>101</td><td>Tom 101</td></tr>
<tr data-id="202"><td>202</td><td>John 202</td></tr>
<tr data-id="303"><td>303</td><td>Van 303</td></tr>
</table>

Comments