Last active
June 26, 2019 22:08
-
-
Save hinchley/5973926 to your computer and use it in GitHub Desktop.
Knockout.js Live Search Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> | |
<title>User Search</title> | |
<meta name="viewport" content="width=device-width"> | |
<style> | |
body { margin: 2em; text-align: center; } | |
form { margin-bottom: 2em; } | |
table { text-align: left; margin: 0 auto; } | |
th, td { padding: .2em; } | |
</style> | |
</head> | |
<body> | |
<div id="container"> | |
<h1>User Search</h1> | |
<form> | |
<input id="search" type="search" name="search" placeholder="Search for a user" data-bind="value: query, valueUpdate: 'keyup'" autocomplete="off" /> | |
</form> | |
<table data-bind="visible: users().length > 0"> | |
<thead><tr><th>Id</th><th>Name</th></tr></thead> | |
<tbody data-bind="foreach: users"> | |
<tr> | |
<td data-bind="text: id"></td> | |
<td data-bind="text: name"></td> | |
</tr> | |
</tbody> | |
</table> | |
</div> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/knockout/2.3.0/knockout-min.js"></script> | |
<script> | |
var users = [ | |
{ id: 'Jack', name: 'Jack Smith' }, | |
{ id: 'Jill', name: 'Jill Jones' }, | |
{ id: 'Jane', name: 'Jane Chung' } | |
]; | |
var viewModel = { | |
users: ko.observableArray([]), | |
query: ko.observable(''), | |
search: function(value) { | |
viewModel.users.removeAll(); | |
if (value == '') return; | |
for (var user in users) { | |
if (users[user].name.toLowerCase().indexOf(value.toLowerCase()) >= 0) { | |
viewModel.users.push(users[user]); | |
} | |
} | |
} | |
}; | |
viewModel.query.subscribe(viewModel.search); | |
ko.applyBindings(viewModel); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Mr. Hinchley,
Thank you for sharing this live search method. It is awesome! I have a question:
if i need to insert address field in it....it is inserted properly but while on searching it only search via name and id????
how to search it via address????