user
user

Reputation: 695

Jquery filter list without case sensitive

I want to filter the list without case sensitive. I want to match only character not match upper case or lower case.

  1. XXXXXXX
  2. yyyyyyy
  3. XXxxx

If I enter "X" in search box it displays both 1 and 3. I added the code below but it match the case sensitive also.

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
    function filter(element) {
        var value = $(element).val();
        $("#theList > li").each(function() {
            if ($(this).text().search(value) > -1) {
                $(this).show();
            }
            else {
                $(this).hide();
            }
        });
    }
</script>
</head>
<body>
<input type="text" onkeyup="filter(this)" />
<ul id="theList">
    <li>xxvxvxx</li>
    <li>yyyyyyyyyy</li>
    <li>rrrrrrrrrr</li>
    <li>vvvvvvvvvvv</li>
    <li>xcvcvdfsdf</li>
    <li>hkjhkhjkh</li>
    <li>xzfgfhfgh</li>
</ul>

</body>
</html>

Upvotes: 10

Views: 14053

Answers (4)

Sushanth --
Sushanth --

Reputation: 55750

You need to use indexOf

$(this).text().search(value)

supposed to be

$(this).text().indexOf(value)

And why do you want to attach your event using the attribute tag.It is a bad practice and should be avoided.

You can use jQuery to attach the event.

$('input').keyup(function() {
    filter(this); 
});

function filter(element) {
    var value = $(element).val().toLowerCase();
    $("#theList > li").each(function () {
        var $this = $(this),
            lower = $this.text;
        if (lower.indexOf(value) > -1) {
            $this.show();
        } else {
            $this.hide();
        }
    });
}

Check Fiddle

Same function a little better using filter

function filter(element) {
    var value = $(element).val().toLowerCase();
    $("#theList > li").hide().filter(function() {
        return $(this).text().toLowerCase().indexOf(value) > -1;
    }).show();
}

Upvotes: 19

Adam Everington
Adam Everington

Reputation: 61

Just Add jQuery.expr[":"].contains = function (a, i, m) { return (a.textContent || a.innerText || "").toUpperCase().indexOf(m[3].toUpperCase())>=0;};

Upvotes: 3

face
face

Reputation: 1505

Just replace

$(this).text().search(value) > -1

with:

$(this).text().search(new RegExp(value, "i")) > -1

and that should do the trick. Here is a working FIDDLE

Upvotes: 5

Maverick
Maverick

Reputation: 478

Try this :

  function filter(element) {
        var value = $(element).val();
        $("#theList > li").hide();
        $("#theList > li:contains('" + value + "')").show();
    }

Upvotes: -1

Related Questions