JavaScript and HTML DOM Reference 1

JavaScript and HTML DOM Reference

const contacts = ['Chris:2232322', 'Sarah:3453456', 'Bill:7654322', 'Mary:9998769', 'Dianne:9384975'];
const para = document.querySelector('p');
const input = document.querySelector('input');
const btn = document.querySelector('button');

btn.addEventListener('click', function() {
  let searchName = input.value.toLowerCase();
  input.value = '';
  for (let i = 0; i < contacts.length; i++) {
    let splitContact = contacts[i].split(':');
    if (splitContact[0].toLowerCase() === searchName) {
      para.textContent = splitContact[0] + '\'s number is ' + splitContact[1] + '.';
    } else {
      para.textContent = 'Contact not found.';

Here is what the above code is Doing:
1. We have an array of contacts.
2. We have a button, an input field, and a paragraph.
3. When the button is clicked, we get the value of the input field and store it in a variable called searchName.
4. We then loop through the contacts array.
5. For each item in the array, we split the item into two parts, the name and the number.
6. We then check if the name is the same as the searchName.
7. If it is, we display the name and number in the paragraph.
8. If it isn't, we display a message saying the contact wasn't found.

Similar Posts