0

I'm very new to the development world (2 months) and I'm trying to get into a selective coding bootcamp. They've asked me to build an addressbook in JS, using HTML, CSS and jQuery, as part of the admissions process. I think I'm pretty close but I can't get my solution to do exactly what it needs.

So this is what I've got so far in JS/jQuery:

// creating an address book constructor, which will contain all our contacts
function AddressBook() {
  this.contacts = [];
}

// creating function that adds contacts to the array
AddressBook.prototype.addContact = function (contactToAdd) {
  this.contacts[this.contacts.length] = contactToAdd;
};

// creating a contact search function
AddressBook.prototype.searchContact = function (searchTerm) {
for (let i = 0; i < this.contacts.length; i++) {
    if (
      searchTerm === this.contacts[i].firstName ||
      this.contacts[i].lastName ||
      this.contacts[i].phoneNumber ||
      this.contacts[i].address
    ) {
      return this.contacts[i];
    }
    return false;
  }
};

//creating a delete function
AddressBook.prototype.deleteContact = function (contactToDelete) {
  for (let i = 0; i < this.contacts.length; i++) {
    if (contactToDelete === this.contacts[i]) {
      delete this.contacts[i];
    }
  }
};

// creating contacts as objects with certain properties and values
function Contact(firstName, lastName, phoneNumber, address) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.phoneNumber = phoneNumber;
  this.address = address;
}

function displayContacts(addressBookDisplay) {
  let htmlForTable = "";
  for (let i = 0; i < addressBookDisplay.contacts.length; i++) {
    const contact = addressBookDisplay.contacts[i];
    htmlForTable +=
      "<tr>" +
      "<td>" +
      contact.firstName +
      "</td>" +
      "<td>" +
      contact.lastName +
      "</td>" +
      "<td>" +
      contact.phoneNumber +
      "</td>" +
      "<td>" +
      contact.address +
      "</td>" +
      "</tr>";
  }
  $("#contact-table-start").html(htmlForTable).appendTo("table");
}

function showContact(contact) {
  if (contact !== undefined) {
    $("#show-search-results").show();
    const contactFirst = contact.firstName;
    const contactLast = contact.lastName;
    const contactPhone = contact.phoneNumber;
    const contactAddress = contact.address;
    $(".first-name").text(contactFirst);
    $(".last-name").text(contactLast);
    $(".phone-number").text(contactPhone);
    $(".address").text(contactAddress);
    let button = $("#delete-button");
    button.empty();
    button.attr("name", contactFirst);
    button.append("<button class='deleteButton'>Delete</button>");
  } else {
    $("#yes-results").hide();
    $("#no-results").text("No result matches your search, try again?");
  }
}

let addressBook = new AddressBook();

$(document).ready(function () {
  $("#add-form").on("submit", function (event) {
    event.preventDefault();

    // creating variables storing input from addform
    const firstNameForm = $("[name=new-first-name]").val();
    const lastNameForm = $("[name=new-last-name]").val();
    const phoneNumberForm = $("[name=new-phone-number]").val();
    const addressForm = $("[name=new-address]").val();

    $("[name=new-first-name]").val("");
    $("[name=new-last-name]").val("");
    $("[name=new-phone-number]").val("");
    $("[name=new-address]").val("");

    let newContact = new Contact(
      firstNameForm,
      lastNameForm,
      phoneNumberForm,
      addressForm
    );

    addressBook.addContact(newContact);
    displayContacts(addressBook);
  });
});

$(document).ready(function () {
  $("#search-form").on("submit", function (event) {
    event.preventDefault();

    // creating variables storing input from searchform
    const searchForm = $("[name=searchterm]").val();
    $("[name=searchterm]").val("");
    const searchcontact = addressBook.searchContact(searchForm);
    showContact(searchcontact);
  });
});

$(document).ready(function () {
  $("#delete-button").on("click", function (event) {
    event.preventDefault();
    let contactDelFirst = $("#delete-button").attr("name");
    let contactToDelete = searchContact(contactDelFirst);
    addressBook.deleteContact(contactToDelete);
    showContact(contactToDelete);
  });
});

This is my HTML if needed:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Elise's Address Book</title>
    <link href="./Style.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
    <script src="./Script.js"></script>
  </head>
  <body>
    <header>
      <h1>Elise's Address Book</h1>
    </header>
    <main>
      <section>
        <div id="search-contact">
          <h2>Search Contacts</h2>
          <form action="#" id="search-form">
            <div>
              <input
                type="text"
                name="searchterm"
                placeholder="Enter contact's full name"
              />
              <input type="submit" />
            </div>
          </form>
        </div>

        <div id="show-search-results">
          <div id="yes-results">
            <h2>Your Contact</h2>
            <p>First Name: <span class="first-name"></span></p>
            <p>Last Name: <span class="last-name"></span></p>
            <p>Phone Number: <span class="phone-number"></span></p>
            <p>Address: <span class="address"></span></p>
            <div id="delete-button"></div>
          </div>
          <div id="no-results">
            <span></span>
          </div>
        </div>

        <div id="contact-list">
          <h2>All Contacts</h2>
          <table id="contact-table-start">
            <tr>
              <th>First Name</th>
              <th>Last Name</th>
              <th>Phone Number</th>
              <th>Address</th>
            </tr>
          </table>
        </div>

        <div id="add-contact">
          <h2>Add New Contact</h2>
          <form action="#" id="add-form">
            <div>
              <input
                type="text"
                name="new-first-name"
                placeholder="Enter first name"
                required
              />
              <input
                type="text"
                name="new-last-name"
                placeholder="Enter last name"
                required
              />
              <input
                type="text"
                name="new-phone-number"
                placeholder="Enter phone number (incl. country code)"
                pattern="^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,6}$"
                required
              />
              <!--check pattern-->
              <input
                type="text"
                name="new-address"
                placeholder="Enter address"
                required
              />
              <input type="submit" />
            </div>
          </form>
        </div>
      </section>
    </main>
    <footer>
      <p>Coded by <em>Elise Verhoeye</em></p>
    </footer>
  </body>
</html>

My main concerns are:

  • My search function isn't working as it should, it only ever outputs the first element in the array of contacts.
  • The new contacts I am adding are being added into the first column, so it's a table within a table, even though my new HTML has td (table data) elements in it.

Does anyone know how I can get this fixed?

Many thanks in advance!

  • 1
    Please provide a proper [mre] of the issue. – CBroe Dec 05 '22 at 10:47
  • Hi CBroe, fair call. I've removed some lines of code I know are working, but given I'm very new to development, I don't really know where the issue situates itself, therefore it's hard for me to remove anything else... if you have any other suggestions, please shoot! – huntingforelise Dec 05 '22 at 11:05
  • In this instance, that didn't mean you should remove more stuff, but present a _reproducible_ example to begin with. Your code interacts with specific HTML, and without seeing that, we can hardly reproduce what it does. – CBroe Dec 05 '22 at 11:08
  • Thanks @CBroe, this makes sense. I've included a code block with my HTML, hopefully that's clearer. – huntingforelise Dec 05 '22 at 11:18
  • `const contact = addressBookDisplay.searchContact(key);` - your searchContact method here gets the numeric keys (0, 1, ...) of the contacts passed - but it doesn't return the _correct_ contact based on that, but always the first one. Why is your `contacts` property of `AddressBook` an object to begin with, and not an array? – CBroe Dec 05 '22 at 11:28
  • Good question. I guess it'd make much more sense if it was an array containing objects as elements, rather than being an object itself. If I change the contacts property to an array, then I guess I can swap out Object.keys(this.contacts).length to this.contacts.length throughout the code. In that case, should I move to a for loop instead of "Object.keys(addressBookDisplay.contacts).forEach(function (key) { const contact = addressBookDisplay.searchContact(key); }"? – huntingforelise Dec 05 '22 at 11:53
  • Hi CBroe, I updated it to a for loop and the list is now outputting new values every time I submit the form, so thanks a lot for calling that out! I still have one persistent issue, which is that the list keeps adding rows (keeping the previous output), rather than refreshing and showing the new, updated list. Do you have any idea how I could make that happen? – huntingforelise Dec 05 '22 at 12:14
  • You are using `after` in that place, that adds to the existing content. `$("#contact-table-start tr:last").after(htmlForTable)` -> `$("#contact-table-start tr:last").html(htmlForTable)` – CBroe Dec 05 '22 at 12:34
  • Thanks CBroe, that indeed helped! I'm so sorry to bother you with this, but I'm still stuck 4 hours later. My search function isn't working as it should, it only ever outputs the first element in the array of contacts. Are you able to take a quick look and see what I'm doing wrong? I have updated my code in the post, reflecting the changes we discussed. – huntingforelise Dec 05 '22 at 17:02
  • You can't use comparison and || like that; https://stackoverflow.com/q/9121395/1427878 – CBroe Dec 06 '22 at 07:05

0 Answers0