I have used a search box to search contact details of persons. There are 4 contacts initially:
1)"Jonathan Buell",5804337551,"family"
2)"Patrick Daniel",8186934432,"work"
3) "Lorraine Winter",3138211928,"work"
4) "Constance Reed",3138211928,"family"
Lets say now if I type j
in input box it should show only Jonathan Buell
if I type Lorr
in input then it should display Lorraine Winter
contact details. If the string does not match if user types xyz
then it should not display any contact.
I tried to implement above search feature but it does not change the content dynamically no change is observed.
Index.html:
var array = [];
function Person(fullName, number, group) {
this.fullName = fullName;
this.number = number;
this.group = group;
array.push(this);
}
var p1 = new Person("Jonathan Buell", 5804337551, "family");
var p2 = new Person("Patrick Daniel", 8186934432, "work");
var p3 = new Person("Lorraine Winter", 3138211928, "work");
var p4 = new Person("Constance Reed", 3138211928, "family");
console.log(array);
function showContacts() {
for (var i in array) {
var id = i;
contactlist.innerHTML +=
`
<ul>
<div>
<p>Name: ` + array[i].fullName + `</p>
<p>Number: ` + array[i].number + `</p>
<p>Group: ` + array[i].group + `</p>
<button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
`
}
}
showContacts();
function search() {
var search = document.getElementById("search").value;
contactlist.innerHTML = '';
for (var i in array) {
if (array[i].fullName.toLowerCase().includes(search.toLowerCase())) {
var id = i;
contactlist.innerHTML =
`
<ul>
<div>
<p>Name: ` + array[i].fullName + `</p>
<p>Number: ` + array[i].number + `</p>
<p>Group: ` + array[i].group + `</p>
<button type="button" class="btn btn-warning" onclick="editContact(` + id + `)">Edit</button>
<button type="button" class="btn btn-danger">Delete</button>
</div>
</ul>
`;
}
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="input-group">
<input type="text" id="search" class="form-control" placeholder="Search">
</div>
</form>
</div>
<div id="contactlist">
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
Screenshot of my app :
Name: \`+ array[i].fullName + \`
`, the whole advantage of [template strings is interpolation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals). Instead, do `Name: ${array[i].fullName}
` – msanford Feb 07 '18 at 14:46