Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add solution for JS3 page2 Exercise #2172

Open
pauly48 opened this issue Aug 9, 2022 · 0 comments
Open

Add solution for JS3 page2 Exercise #2172

pauly48 opened this issue Aug 9, 2022 · 0 comments
Labels
curriculum lesson content

Comments

@pauly48
Copy link
Contributor

pauly48 commented Aug 9, 2022

Below section of exercise question is missing appropriate solution.
image


A HTML page with following solution code needs to be implemented and linked.

<h1>Friends List</h1>
Name: <input class="name">
Age: <input class="age">
<button class="add">Add</button>
<div class="box"></div>

<script>
    const list = document.querySelector('.box')
    const nameInput = document.querySelector('.name')
    const ageInput = document.querySelector('.age')
    const addB = document.querySelector('.add')

    const friendsData = localStorage.getItem('friends') || '[]'
    const friends = JSON.parse(friendsData)


    const render = () => {
        const newFriendsData = JSON.stringify(friends)
        localStorage.setItem('friends', newFriendsData)


        list.innerHTML = friends.reduce((acc, e, i) => {
            return acc + `
            <div>
                <h2 class="friendName">${e.name}</h2>
            </div>
            `
        }, '')

        const nameElements = document.querySelectorAll('.friendName')
        nameElements.forEach((e, i) => {
            e.onclick = () => {

                alert(friends[i]['age'])
            }
        })
    }

    addB.onclick = () => {

        friends.unshift({
            name: nameInput.value,
            age: ageInput.value
        })

        render()
    }

    render()
</script>
@flacial flacial added the curriculum lesson content label Aug 10, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
curriculum lesson content
Projects
None yet
Development

No branches or pull requests

2 participants