Just learning Javascript

I’m just learning Javascript. I’m trying to create a basic application, a form asks for a first and last name. I want to check whether that name exists in an array, if it exists an error is given as an alert. if the name doesn’t exist, the name is added to the array and displayed to output. I’ve added the code to this, but for some reason the program is still allowing duplicate names. Is there anyone who can help with this? Also, my clear list is only clearing the last element rather than the entire array. Anyone know this one too?

let guest_list = []

function getGuestList() {
    if (localStorage.getItem('names') && localStorage.getItem("names") != '[ ]') {
        return JSON.parse(localStorage.getItem('names'))
    } else {
        return guest_list
    }
}

function addNewGuest(event) {
    event.preventDefault()
    let f = document.querySelector("#first_name").value
    let l = document.querySelector("#last_name").value
    
    let names = getGuestList()

    if (f === '' || l === '') {
        alert('First and last name required')
    } 

    if (f && l) {
        let name = { fName: f, lName: l} 
        if (guest_list.includes(name)) {
            alert('Name already exists')
        } else {
            names.push(name)
            localStorage.setItem('names', JSON.stringify(names))
        }
    }
    displayGuestList()
    document.querySelector("#first_name").value = ''
    document.querySelector("#last_name").value = ''
}

function clearForm(event) {
    let names = getGuestList()
    for (let n of names) {
        localStorage.clear(n)
    }
    displayGuestList()
}

document.querySelector("#myForm").onsubmit = addNewGuest
document.querySelector("#reset").onclick = resetForm
document.querySelector("#clear").onclick = clearList
displayGuestList()

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (').

Can you provide a full working example (with the HTML).


If you use includes on an array of objects, it will do a reference comparison. If the two objects are the same it will be true, if they are not the same objects but contain the same key/values it will be false.

const user1 = {
  name: 'John',
  surname: 'Smith',
};

const user2 = {
  name: 'John',
  surname: 'Smith',
};

const user3 = {
  name: 'Jill',
  surname: 'Smith',
};

const users = [user1]
console.log(users);

console.log(user1); // { name: 'John', surname: 'Smith' }
console.log(users.includes(user1)); // true

console.log(user2); // { name: 'John', surname: 'Smith' }
console.log(users.includes(user2)); // false

console.log(user3); // { name: 'Jill', surname: 'Smith' }
console.log(users.includes(user3)); // false

my HTML:

<div class="container">
    
      <form id="myForm" class="" method="post">
        <div class="mb-3">
          <label for="first_name" class="form-label">Guest's first name</label>
          <input type="text" class="form-control" id="first_name" name="first_name" placeholder="First name goes here">
        </div>
        <div class="mb-3">
          <label for="last_name" class="form-label">Guest's last name</label>
          <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Last name goes here">
        </div>
        <button type="submit" class="btn btn-primary" id="addGuest">Add a guest</button>
        <button type="button" class="btn btn-danger to-cancel" id="reset">Reset</button>
      </form>
    </div>
    
    <br><br><br>
    <div class="container">
      <nav class="navbar navbar-expand-lg bg-light">
        <div class="container-fluid">
          <div class=" display-4">Registered Guests</div>
            <div>
              <form class="d-flex" role="search">
                <button class="btn btn-outline btn-danger" type="button" id="clear">Clear all</button>
              </form>
            </div>
        </div>
      </nav>
      <table class="table table-striped">
        <thead>
          <tr>
            <th scope="col">First name</th>
            <th scope="col">Last name</th>
          </tr>
        </thead>
        <tbody class="table-group-divider" id="guestList">
          
        </tbody>
      </table>
    </div>

my JS

let guest_list = [
    
]


function getGuestList() {
    if (localStorage.getItem('names') && localStorage.getItem("names") != '[]') {
        return JSON.parse(localStorage.getItem('names'))
    } else {
        return guest_list
    }
}



//add name to the guest_list array. First checks whether the first name or the last name is empty. If it is, an alert pops.
//Then, if first name and last name hold values, create a name variable to hold the first name and the last name. the name passes to the checkName() function, if function returns true, an alert pops, if it returns false the name is added to the array.

function addNewGuest(event) {
    event.preventDefault()
    let f = document.querySelector("#first_name").value
    let l = document.querySelector("#last_name").value
    
    let names = getGuestList()

    if (f === '' || l === '') {
        alert('First and last name required')
    } 

    if (f && l) {
        let name = { fName: f, lName: l} 
        if (guest_list.includes(name)) {
            alert('Name already exists')
        } else {
            names.push(name)
            localStorage.setItem('names', JSON.stringify(names))
        }
    }

    //if (f && l) {
    //    let name = {  fName: f, lName: l }
    //    names.push(name)
    //    localStorage.setItem('names', JSON.stringify(names))
    //}
    displayGuestList()
    document.querySelector("#first_name").value = ''
    document.querySelector("#last_name").value = ''
}

function resetForm(event) {
    document.querySelector("#first_name").value = ''
    document.querySelector("#last_name").value = ''
}

function displayGuestList() {
    let names = getGuestList()
    let guest_html = ''
    let ndx = 0
    for (let n of names) {
        guest_html += `
            <tr>
                <td>${n.fName}</td>
                <td>${n.lName}</td>
            </tr>
        `
        ndx++
    }
    document.querySelector("#guestList").innerHTML = guest_html    
}
  
function clearList(event) {
    let names = getGuestList()
    for (let n of names) {
        localStorage.clear(n)
    }
    displayGuestList()
}


document.querySelector("#myForm").onsubmit = addNewGuest
document.querySelector("#reset").onclick = resetForm
document.querySelector("#clear").onclick = clearList
displayGuestList()

Did you understand what I was saying in the above post?

Object compare doesn’t work like that. You have to check the values inside the objects or you can use JSON.stringify() although that is not always advisable.

console.log({} === {}); // false

const user1 = {
  name: 'John',
  age: 30,
};

const user2 = {
  name: 'John',
  age: 30,
};

console.log(user1 === user1); // true
console.log(user1 === user2); // false
console.log(JSON.stringify(user1) === JSON.stringify(user2)); // true

I think so, let me do some checking and see what I can whip up.

2 posts were split to a new topic: View JS YouTube course

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.