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>
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"
Post a Comment