Search and Filter Array in JavaScript
Introduction: Hello Guys, “Welcome back” Today i am here with another one new great article. In this article I will explain that how to search and filter array in Javascript
Code for HTML Page
On the HTML page there will be Two Controls, one is text box with the id named txt_filter for to enter the input by the user and this text box is assigned with onkeyup event handler. And other one control is Span with the id named lbl_output for displaying the filtered records
<input type="text" onkeyup="Filter(this.value)" id="txt_filter" />
<br />
<span id="lbl_output"></span>
Search and Filter Array in JavaScript
There will be Filter JavaScript function is called in the window.onload and TextBox onkeyup event handler,.
Filter JavaScript function
FOR loop will executed in the Array an Array of names is defined Inside the Filter Javascript function
Inside the Filter Javascript function, and a FOR loop is executed over it.
Then, inside the FOR loop, a condition is performed for checking whether the Array index is not equal to -1 then Array will be copied inside another one Array named filterArr.
After this, a check is performed if the Array length is greater than 0 then filtered result will be shown in the HTML SPAN control.
Below i am giving complete code for the HTML page. You can copy and paste complete code inside the HTML page for execute the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
body { font-family: Arial; font-size: 10pt; }
</style>
<script type="text/javascript">
window.onload = function () {
Filter("");
};
function Filter(value) {
var arr = [
"Bharat Bhushan",
"Sanjeev Kumar",
"Nancy Kohli",
"Ruhika",
"Danish Verma",
"Micheal Mike",
"Sachin Verma",
"Nishant Malhotra",
"Harry Sharma",
"Aman Salotra"
];
var filterArr = [];
for (var i in arr) {
if (arr[i].toLowerCase().indexOf(value.toLowerCase()) != -1) {
filterArr[filterArr.length] = arr[i];
}
}
if (filterArr.length > 0) {
document.getElementById("lbl_output").innerHTML = filterArr.join("<br />");
} else {
document.getElementById("lbl_output").innerHTML = "No matches!";
}
}
</script>
</head>
<body>
<input type="text" onkeyup="Filter(this.value)" id=" txt_filter " />
<br />
<span id=" lbl_output "></span>
</body>
</html>
Conclusion: In above code, I explained that how to search and filter array in Javascript. This code is very helpful for every developer. Bye Bye and take care of your Developers. We will come back shortly with the new article.
Regards
Using Asp.net
Comments
Post a Comment