jQuery Contains

02/28/2024

This is a short example on how to use jQuery's :contains selector.

Example

Suppose we have a table like this:

Example table
First nameLast nameEmailCountryDob
JohnyWalkerjohny.walker@whiskey.comScotland1/1/1920
nikhilVartaknikhil.vartak@hotmail.co.inindia12/5/1986
PeterJamesjames_peter@hotmail.comgermany5/10/1960
nikhilVartaknikhil.vartak@hotmail.comindia11/27/1984
PeterJamesjames_peter@hotmail.comgermany5/10/1960
jackDanielj'daniels@whiskey.comUSA1/10/1846
nikhilVartaknikhil.vartak@hotmail.co.inindia12/5/1986
PeterJamesjames_peter@hotmail.comgermany5/10/1960
jackDanielj'daniels@whiskey.comUSA1/10/1846
jackDanielj'daniels@whiskey.comUSA1/10/1846
MarkAndersonanderson_m@gmail.comcanada2/29/1980
jackDanielj'daniels@whiskey.comUSA1/10/1846
nikhilVartaknikhil.vartak@hotmail.co.inindia12/5/1986
jackDanielj'daniels@whiskey.comUSA1/10/1846
PeterJamesjames_peter@hotmail.comgermany5/10/1960

If we have an input, we could use this code to filter the results:


function searchTable() {
    var input = $('#search-input').val();
    $('#data-table').find('tr:not(:contains(' + input + '))').addClass('d-none'); // hide non matches
    $('#data-table').find('tr:contains(' + input + ')').removeClass('d-none');    // show mathing tables
}

© 2024 by Ryan Rickgauer