Proxy > Gmail Facebook Yahoo!

Search and Filter Array in JavaScript




This is a short code snippet article where I am describing how to filter array client side in JavaScript.
JavaScript Snippet
Below is the snippet that filters the JavaScript array of strings based on the text typed in the textbox. The filtered results are displayed in HTML span dynamically as you type.
You are reading MyCodeLogic
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript">
    var arr = ["Ana Trujillo",
        "Antonio Moreno",
        "Thomas Hardy",
        "Christina Berglund",
        "Hanna Moos",
        "Frédérique Citeaux",
        "Martín Sommer",
        "Laurence Lebihan",
        "Victoria Ashworth",
        "Janine Labrune"];
    function Filter(value) {
        var filterArr = [];
        for (var i in arr) {
            if (arr[i].toLowerCase().indexOf(value.toLowerCase()) != -1) {
                filterArr[filterArr.length] = arr[i];
            }
        }
        var result = "";
        for (var i in filterArr) {
            result += filterArr[i] + "<br />";
        }
        if (result != "") {
            document.getElementById("lblResult").innerHTML = result;
        } else {
            document.getElementById("lblResult").innerHTML = "No matches!";
        }
    }
    window.onload = function () {
        Filter("");
    };
</script>
</head>
<body>
<input type = "text" onkeyup = "Filter(this.value)" id = "txtFilter" /><br />
<span id="lblResult"></span>
</body>
</html>
Downloads
You are reading MyCodeLogic
You can download the sample source code using the download link provided below.
FilterArrayInJavaScript.zip


Responses

0 Respones to "Search and Filter Array in JavaScript"


Send mail to your Friends.  

Expert Feed

 
Return to top of page Copyright © 2011 | My Code Logic Designed by Suneel Kumar