1

I use this function below to quickly find an item in a table
My problem is that this function only searches for text that contains the search string in the given table
I have been trying my best to modify it to match only the text that begins with the search string but not working.

function searchTable(inputVal)
{
    var table = $('#supplier_table_body');
    table.find('tr').each(function(index, row)
    {
        var allCells = $(row).find('td');
        if(allCells.length > 0)
        {
            var found = false;
            allCells.each(function(index, td)
            {
                var regExp = new RegExp(inputVal, '^i');
                if(regExp.test($(td).text()))
                {
                    found = true;
                    return false;
                }
            });
            if(found == true)$(row).show();else $(row).hide();
        }
    });
}

Here is my jquery

        $('#itemname').keyup(function()
    {
        searchTable($(this).val());
    });
1
  • 1
    As an aside, if(found == true) ... else ... can all be replaced by $(row).toggle( found ) Commented Feb 13, 2013 at 13:35

4 Answers 4

3

The string start anchor is not a regex modifier flag, but needs to be part of the expression:

var regExp = new RegExp('^'+inputVal, 'i');
Sign up to request clarification or add additional context in comments.

Comments

1

I think you should use \b: new RegExp("\\b" + inputVal, "i"). It finds a match that begins with inputVal.

1 Comment

and also use mg flags next to your i in case the content of that cell is multilined.
1

Not sure if it works, but you may try to add a caret ( ^ ) before the inputVal, while creating the RegExp.

This should only allow words starting with inputVal.

Cheers,

EDIT:

Like so :

new RegExp("^" + inputVal, "i")

1 Comment

Thanx a lot Romain Sertelon This eventually worked for me. var regExp = new RegExp("^"+ inputVal, "i");
0

This answer posted as a community wiki answer because I think it solves the problem you're having and simplifies your code (but is too long to post as a comment), so I'd suggest, though currently untested, amending your function to:

function searchTable(needle){
    var table = $('#supplier_table_body'),
        cells = table.find('td');
    cells.filter(function(){
        return this.textContent.indexOf(needle) !== 0;
    }).closest('tr').hide();
}

Simple proof of concept.

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.