impactbyte-haku / projects

🌐 Projects
https://gitlab.com/impactbyte/learn/course-fullstackweb
9 stars 1 forks source link

Project DOM Events #27

Open mhaidarhanif opened 5 years ago

mhaidarhanif commented 5 years ago

Submit here.

mhaidarhanif commented 5 years ago
<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Project JavaScript</title>

    <link rel="stylesheet" href="index.css" />
  </head>
  <body>
    <header id="header">
      <h1>Pemilu KW</h1>
    </header>

    <main id="content"></main>

    <form id="comment-form">
      <textarea id="comment" name="comment" cols="30" rows="10"></textarea>
      <input type="submit" value="Post Comment" />
    </form>

    <script src="index.js"></script>
    <script src="form.js"></script>
  </body>
</html>
const content = document.getElementById('content')

const dataCandidates = [
  {
    id: 1,
    name: 'Jokowi Amin',
    result: 1
  },
  {
    id: 2,
    name: 'Prabowo Sandi',
    result: 1
  },
  {
    id: 3,
    name: 'Nurhadi Aldo',
    result: 100
  }
]

const displayCandidates = () => {
  content.innerHTML = ''

  dataCandidates.forEach(candidate => {
    const { id, name, result } = candidate

    content.innerHTML += `
    <section id="candidate-${id}">
      <h1>${id}. ${name}</h1>
      <button id="vote-${id}">
        Vote ${name}
      </button>
      <span>Result: ${result}</span>
    </section>`
  })
}

const addEventListeners = () => {
  dataCandidates.forEach((candidate, index) => {
    const { id, name, result } = candidate

    document.getElementById(`vote-${id}`).addEventListener('click', function() {
      dataCandidates[index].result += 1
      displayCandidates()
      addEventListeners()
    })
  })
}

displayCandidates()
addEventListeners()
const commentForm = document.getElementById('comment-form')

commentForm.onsubmit = function() {
  event.preventDefault()

  const comment = document.getElementById('comment').value

  alert(comment)
}
mhaidarhanif commented 5 years ago
yevgenysiregar commented 5 years ago