<div class="input-group mb-3">
<input type="text" id="contactSearch" class="form-control" placeholder="Try Mary, Chris, Bill or Sarah">
<button id="searchBtn" class="btn btn-primary">Search</button>
</div>
<p id="searchResult" class="h5"></p>
<script>
// This example demonstrates how to search for a phonenumber for a specific name.
//allows users to find a phone number by entering a name
// contacts is an array of strings, each containing a name and a phone number separated by a colon
const contacts = [
"Chris:2232322",
"Sarah:3453456",
"Bill:7654322",
"Mary:9998769"
];
const para = document.querySelector("#searchResult");
const input = document.querySelector("#contactSearch");
const btn = document.querySelector("#searchBtn");
// addEventListener is used to listen for click events on elements like on this button
// When the button is clicked, the arrow function inside is executed
btn.addEventListener("click", () => {
//toLowerCase is used to make the search case-insensitive
//value is used to get user input from input field,
const searchName = input.value.toLowerCase();
input.value = "";
//focus is used to set the focus on the input field
input.focus();
para.textContent = "";
const foundContact = contacts.find(contact => {
const [name, phone] = contact.split(":");
return name.toLowerCase() === searchName.toLowerCase();
});
if (foundContact) {
const [name, phone] = foundContact.split(":");
para.textContent = `${name}'s number is ${phone}`;
} else {
para.textContent = "Contact not found.";
}
if (para.textContent === "") {
para.textContent = "Contact not found.";
}
});//end click event
</script>