Задать вопрос
@Meetyourmaker

Как изменить объект в массиве через модальное окно по клику?

Вот код, хочу реализовать такой функционал, при нажатии на кнопку, которая находится в объекте, открывается модальное окно, я получаю данные из этого окна и на основе этих данных редактирую нужный мне объект, в котором эта кнопка находилась

const newPersonBtn = document.getElementById('new-person')
const modalWindow = document.getElementById('modal')
const closeModal = document.getElementById('close-modal')
const appendPerson = document.getElementById('append-person')
const overlay = document.getElementById('overlay')
const btnDeleteLastUser = document.getElementById('delete-last-user')
let editUserBtn = document.getElementById('edit')
let userName = document.getElementById('name')
let userLastname = document.getElementById('last-name')
let userCountry = document.getElementById('country')
let userCity = document.getElementById('city')

// data
const userArr = []

// function open modal
const showModalWindow = () => {
   modalWindow.classList.add('show')
   overlay.classList.add('overlay')
}
// function close modal
const closeModalWindow = () => {
   modalWindow.classList.remove('show')
   overlay.classList.remove('overlay')
}

// open modal
newPersonBtn.addEventListener('click', () => {
   showModalWindow()
   editUserBtn.classList.add('none')
   userName.value = ''
   userLastname.value = ''
   userCountry.value = ''
   userCity.value = ''
})

// close modal
overlay.addEventListener('click', closeModalWindow)
closeModal.addEventListener('click', () => {
   closeModalWindow()
})

document.addEventListener('keydown', (e) => {
   if (e.key === 'Escape' && modalWindow.classList.contains('show')) {
      closeModalWindow()
   }
})

// add user
appendPerson.addEventListener('click', () => {

   if (userName.value === '' || userLastname.value === '' || userCountry.value === '' || userCity.value === '') {
      alert('Заполните все поля')
   } else {
      newUser(userArr.length + 1, userName.value, userLastname.value, userCountry.value, userCity.value)
      drawTable()
      closeModalWindow()
      console.log(userArr)

   }

})
// delete last user
btnDeleteLastUser.addEventListener('click', () => {
   userArr.pop()
   drawTable()
})


const newUser = (id, name, lastName, country, city, ) => {
   userArr.push({
      id: id,
      name: name,
      lastName: lastName,
      country: country,
      city: city,
      editUser: `<a href="#" class="link-dark edit-user" onclick="editUser(${id})">
      <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-pencil-square" viewBox="0 0 16 16">
  <path d="M15.502 1.94a.5.5 0 0 1 0 .706L14.459 3.69l-2-2L13.502.646a.5.5 0 0 1 .707 0l1.293 1.293zm-1.75 2.456-2-2L4.939 9.21a.5.5 0 0 0-.121.196l-.805 2.414a.25.25 0 0 0 .316.316l2.414-.805a.5.5 0 0 0 .196-.12l6.813-6.814z"/>
  <path fill-rule="evenodd" d="M1 13.5A1.5 1.5 0 0 0 2.5 15h11a1.5 1.5 0 0 0 1.5-1.5v-6a.5.5 0 0 0-1 0v6a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5v-11a.5.5 0 0 1 .5-.5H9a.5.5 0 0 0 0-1H2.5A1.5 1.5 0 0 0 1 2.5v11z"/>
</svg>
      </a>`,
      removeUser: `<button type="button" class="btn-close" onClick="removeUser(${id})"></button>`,
   })
}



// draw table 
const drawTable = () => {
   let tableHtml = ''
   userArr.forEach(elem => {
      tableHtml += `
      <tr class="align-middle">
        <td class="table-warning td-user">${elem.id}</td>
        <td class="table-warning td-user">${elem.name}</td>
        <td class="table-warning td-user">${elem.lastName}</td>
        <td class="table-warning td-user">${elem.country}</td>
        <td class="table-warning td-user">${elem.city}</td>
        <td class="table-warning td-user">${elem.editUser}</td>
        <td class="table-warning td-user">${elem.removeUser}</td>
      </tr>`
   })
   document.getElementById('tbody').innerHTML = tableHtml
}

// remove user
const removeUser = (id) => {
   if (userArr.length > 0) {

      for (let index = 0; index < userArr.length; index++) {
         let user = userArr[index];
         if (user.id === id) {
            userArr.splice(index, 1)
            drawTable()
         }
      }

   }
}


function editUser(id) {
   showModalWindow()
   editUserBtn.classList.remove('none')
}


<!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>Table</title>
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="main.css" />
  </head>
  <body>
    <div class="container pt-2 pb-2">
      <!-- header -->
      <div class="row mb-3">
        <div class="col-12">
          <div
            class="header d-flex justify-content-between align-items-center p-2 border border-3 border-warning"
          >
            <h1 class="h2">Table</h1>
            <div class="btn-container">
              <button type="button" class="btn btn-dark" id="new-person">
                New user
              </button>
              <button
                type="button"
                class="btn btn-warning ms-3"
                id="delete-last-user"
              >
                Delete last user
              </button>
            </div>
          </div>
        </div>
      </div>
      <!-- table -->
      <div class="">
        <table
          class="table table-responive table-bordered border-3 border-warning align-middle"
        >
          <thead id="thead">
            <tr class="table-info align-middle">
              <th>ID</th>
              <th>Name</th>
              <th>Last Name</th>
              <th>Country</th>
              <th>City</th>
              <th>Edit user</th>
              <th>Remove</th>
            </tr>
          </thead>
          <tbody id="tbody"></tbody>
        </table>
      </div>
    </div>
    <!-- modal -->
    <div class="modal-dialog hidden" id="modal">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">New person</h5>
        </div>
        <div class="modal-body">
          <form>
            <div class="mb-1">
              <label for="name" class="col-form-label">Name:</label>
              <input type="text" class="form-control" id="name" />
            </div>
            <div class="mb-1">
              <label for="last-name" class="col-form-label">Last name:</label>
              <input type="text" class="form-control" id="last-name" />
            </div>
            <div class="mb-1">
              <label for="country" class="col-form-label">Country:</label>
              <input type="text" class="form-control" id="country" />
            </div>
            <div class="mb-1">
              <label for="city" class="col-form-label">City:</label>
              <input type="text" class="form-control" id="city" />
            </div>
          </form>
        </div>
        <div class="modal-footer" id="modal-footer">
          <button type="button" class="btn btn-secondary" id="close-modal">
            Close
          </button>
          <button type="button" class="btn btn-primary" id="append-person">
            Create
          </button>
          <button type="button" class="btn btn-success" id="edit">Edit</button>
        </div>
      </div>
    </div>
    <div class="hidden" id="overlay"></div>
    <!-- scripts -->
    <script src="main.js"></script>
    <script
      src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>
  • Вопрос задан
  • 71 просмотр
Подписаться 1 Средний 6 комментариев
Пригласить эксперта
Ответы на вопрос 1
Rst0
@Rst0
как-то так

тестовый пользователь для наглядности, эту функцию можно удалить
Ответ написан
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы