Skip to content

Instantly share code, notes, and snippets.

@amitgupta15
Created February 24, 2020 22:05
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save amitgupta15/2240838e112ba073c24877583043fa34 to your computer and use it in GitHub Desktop.
Save amitgupta15/2240838e112ba073c24877583043fa34 to your computer and use it in GitHub Desktop.
Complete code listing
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Search a List</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
ul {
list-style: none;
}
li {
padding: 10px 0;
line-height: 1.2rem;
}
</style>
</head>
<body>
<form id="search-books">
<label for="search">Search:</label>
<input type="text" name="search" id="search">
<button name="search_btn">Search</button>
<button name="reset" type="reset">Reset</button>
</form>
<div id="app"></div>
</body>
<script>
var books = [
{
"title": "Cracking the coding interview",
"subtitle":"189 programming questions and solutions",
"author":"Gayle Laakmann McDowell",
"category":"Programming",
"publisher":"CareerCup, LLC"
},
{
"title": "No friend but the mountains",
"subtitle":"Writing from manu prison",
"author":"Behrouz Boochani",
"category":"Literature",
"publisher":"Pan Macmillan Australia"
},
{
"title": "Indian Harvest",
"subtitle":"Classic and contemporary vegetarian dishes",
"author":"Vikas Khanna",
"category":"Cuisine",
"publisher":"Bloomsbury USA"
},
{
"title": "Upheaval",
"subtitle":"Turning points for nations in crisis",
"author":"Jared Diamond",
"category":"Politics",
"publisher":"Little, Brown & Company"
},
{
"title": "Algorithms",
"subtitle":"Fourth Edition",
"author":"Robert Sedgewick, Kevin Wayne",
"category":"Programming",
"publisher":"Addison Wesley"
},
{
"title": "How We Die",
"subtitle":"Reflections on Life's Final Chapter",
"author":"Sherwin B. Nuland",
"category":"Literature",
"publisher":"Vintage"
},
{
"title": "The Circle",
"subtitle":"",
"author":"Dave Eggers",
"category":"Fiction",
"publisher":"Vintage"
},
{
"title": "The Algorithm Design Manual",
"subtitle":"",
"author":"Steven S. Skiena",
"category":"Programming",
"publisher":"Springer"
},
{
"title": "I Contain Multitudes",
"subtitle":"The microbes within us and a grander view of life",
"author":"Ed Yong",
"category":"Science",
"publisher":"HarperCollins"
},
{
"title": "The Silkwarm",
"subtitle":"A Cormoran Strike Novel",
"author":"Robert Galbraith",
"category":"Literature",
"publisher":"Mulholland Books"
},
{
"title": "Cosmos",
"subtitle":"",
"author":"Carl Sagan",
"category":"Science",
"publisher":"Ballantine Books"
},
{
"title": "Comanche Moon",
"subtitle":"",
"author":"Larry McMurtry",
"category":"Science",
"publisher":"Simon & Schuster"
},
{
"title": "Nine Pints",
"subtitle":"A journey through the money, medicine, and mysteries of blook",
"author":"Rose George",
"category":"Science",
"publisher":"Metropolitan books"
},
]
var render = function(data) {
var app = document.getElementById('app');
var booksHTMLString = '<ul>'+
data.map(function(book){
return '<li>'+
'<strong>Title: </strong>' + book.title + '<br/>' +
'<strong>Subtitle: </strong>' + book.subtitle + '<br/>' +
'<strong>Author: </strong>' + book.author + '<br/>' +
'<strong>Category: </strong>' + book.category + '<br/>' +
'<strong>Publisher: </strong>' + book.publisher + '<br/>' +
'</li>';
}).join('');
+ '</ul>';
app.innerHTML = booksHTMLString;
}
render(books);
var handleSearch = function(event) {
event.preventDefault();
// Get the search terms from the input field
var searchTerm = event.target.elements['search'].value;
// Tokenize the search terms and remove empty spaces
var tokens = searchTerm
.toLowerCase()
.split(' ')
.filter(function(token){
return token.trim() !== '';
});
if(tokens.length) {
// Create a regular expression of all the search terms
var searchTermRegex = new RegExp(tokens.join('|'), 'gim');
var filteredList = books.filter(function(book){
// Create a string of all object values
var bookString = '';
for(var key in book) {
if(book.hasOwnProperty(key) && book[key] !== '') {
bookString += book[key].toString().toLowerCase().trim() + ' ';
}
}
// Return book objects where a match with the search regex if found
return bookString.match(searchTermRegex);
});
// Render the search results
render(filteredList);
}
};
document.addEventListener('submit', handleSearch);
document.addEventListener('reset', function(event){
event.preventDefault();
render(books);
})
</script>
</html>
@riteshcgiri
Copy link

if i have to search something in div box how can i do this?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur, deleniti corporis. Temporibus repudiandae porro veniam libero autem amet maxime, laudantium sapiente placeat atque, quo aspernatur perspiciatis architecto perferendis rem ea.

for example i need to search a word form this div.
can you explain...

@amitgupta15
Copy link
Author

if i have to search something in div box how can i do this?

Lorem ipsum dolor sit amet consectetur adipisicing elit. Consequatur, deleniti corporis. Temporibus repudiandae porro veniam libero autem amet maxime, laudantium sapiente placeat atque, quo aspernatur perspiciatis architecto perferendis rem ea.
for example i need to search a word form this div. can you explain...

If you are searching on a DIV, your DIV will need an ID

<div id="searchme">
Lorem ipsum....
</div>

In Javascript, you can write the code as follows:

let divString = document.getElementById('searchme').innerHTML;

divString.search('Lorem'); // Will return 0 I believe since it is the index for the first character of the word Lorem in your DIV.

HTH,
Amit

@osborneoswald
Copy link

Thank you very much for this functionality. However, can I hide the entire book object from showing up initially until when searched out?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment