I'm using jQuery contains to show records in a page that contains information that matches a search field. This functions works very well, a bit too good actually...

The challenge is that it also searches for matching words in SELECT elements that is inside the table column.

$(this).find('td:nth-child(2)').each(function () {
    if ($(this).is(':contains(' + fValue + ')')) {
        $(this).closest('tr').show();
        bFound = true;
    } else {
        $(this).closest('tr').hide();
    }
});

I have tried multiple methods to achieve the goal, but no still no luck…

if ($(this).is(':contains(' + fValue + ')').not('select')) { //error


if ($(this).is(':contains(' + fValue + '):not(select)')) { //same result as without the not

Recommended Answers

All 5 Replies

Can you post some of the table, including the select.

A working solution, although maybe not the fastest, could be:

$(this).find('td:nth-child(2)').each(function()
{
    // Create a clone of the <td>, so that we can modify its contents.
    var clone = $(this).clone();

    // Remove the <select> from the cloned <td>, so that we can properly use
    // the :contains selector.
    clone.find('select').remove();

    // Check if the clone contains value X.
    if(clone.is(':contains(' + fValue + ')'))
    {
        $(this).closest('tr').show();
        bFound = true;
    } 
    else
    {
        $(this).closest('tr').hide();
    }
});

minitauros: You are absolutely into something there, but I was hoping there was a smoother method somehow in jQuery…

paulkd:

<table>
    <tr><td></td><td>this row should not be visible if i search for some text<select><option>test</option></select></td></tr>
    <tr><td></td><td>but this one on the other hand should be visible when you try to search for the keyword test...</td></tr>
</table>

The example above shows both rows when you use fValue='test'

Well I cannot think of any smoother way to achieve that using jQuery, except... maybe...

What if you place the text you want to search inside a <p> element, and then use is.(':contains(test)') on that <p>? :) That way you can ignore the <select>.

Following minitauros's cloning idea I came up with this...

var fValue = 'test';
var $tableBody = $("#yourTableId tbody");
var $clone = $tableBody.clone();
$clone.find("select").remove();
$clone.find("td:nth-child(2)").not(":contains("+fValue+")").parent().remove();
$tableBody.parent().html($clone);

It replaces your table. I've added some further selection data for my tests.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.