Edit button in each row of table using same Bootstrap modal as add button

21 Views Asked by At

I want to use one modal for adding and editing rows in the table, but i dont know what JS code write for this, because add button is outside of the table and the edit buttons can be added many times. Also i want modal to change its title and button`s text for editing and adding. Make sure to use listeners. It will be good to add JS code for the delete buttons as well. The data should be stored only in a table, there is no reason to store it somewhere else.

There is html:

<div class="container-fluid p-4">
                            <div class="row align-items-center">
                                <div class="col-9 col-lg-11">
                                    <h1>Students</h1>
                                </div>
                                <div class="col-3 col-lg-1 text-end">
                                    <button type="button" class="rounded-4" data-bs-toggle="modal" data-bs-target="#addModal" data-bs-whatever="add">
                                        <i class="fa-solid fa-plus"></i>
                                    </button>
                                </div>
                            </div>                                                                                      
                            <div class="table-responsive border border-secondary">
                                <table class="table text-nowrap text-center m-0">
                                    <thead>
                                        <tr>
                                        <th class="bg-body-secondary"><input type="checkbox"  id="myCheckbox"></th>
                                        <th class="bg-body-secondary">Group</th>
                                        <th class="bg-body-secondary">Name</th>
                                        <th class="bg-body-secondary">Gender</th>
                                        <th class="bg-body-secondary">Birthday</th>
                                        <th class="bg-body-secondary">Status</th>
                                        <th class="bg-body-secondary">Options</th>
                                        </tr>
                                    </thead>
                                    <tbody id="stList">
                                    </tbody>
                                </table>
                            </div>
                            <!-- Modal -->
                            <div class="modal fade" id="addModal" tabindex="-1" aria-labelledby="addModalLabel" aria-hidden="true">
                                <div class="modal-dialog">
                                <div class="modal-content">
                                    <div class="modal-header">
                                    <h5 class="modal-title" id="addModalLabel">Add student</h5>
                                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                    </div>
                                    <div class="modal-body">
                                        <form id="addForm">
                                            <div class="mb-3">
                                                <label for="group" class="form-label">Group:</label>
                                                <select id="group" class="form-select" aria-label="Default select example" required>
                                                    <option selected disabled value="0">Select group</option>
                                                    <option>PZ-21</option>
                                                    <option>PZ-22</option>
                                                    <option>PZ-23</option>
                                                    <option>PZ-24</option>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label for="fname" class="form-label">First name:</label>
                                                <input type="text" class="form-control" id="fname" required placeholder="Enter your first name" required>
                                            </div>
                                            <div class="mb-3">
                                                <label for="lname" class="form-label">Last name:</label>
                                                <input type="text" class="form-control" id="lname" required placeholder="Enter your last name" required>
                                            </div>
                                            <div class="mb-3">
                                                <label for="gender" class="form-label">Gender:</label>
                                                <select id="gender" class="form-select" aria-label="Default select example" required>
                                                    <option selected disabled value="0">Select gender</option>
                                                    <option>Male</option>
                                                    <option>Female</option>
                                                </select>
                                            </div>
                                            <div class="mb-3">
                                                <label for="birthday" class="form-label">Birthday:</label>
                                                <input type="date" id="birthday" class="form-control"
                                                    min="1930-01-01" max="2008-12-31" 
                                                    title="Select the birthday date from the drop-down calendar" required>
                                            </div>
                                            <div class="row mb-3">
                                                <div class="col-auto">
                                                    <label class="form-check-label" for="statusSw">Status:</label>
                                                </div>
                                                <div class="col-auto form-check form-switch">
                                                    <input class="form-check-input" type="checkbox" role="switch" id="statusSw">
                                                </div>
                                            </div>
                                            <div class="d-flex justify-content-end">
                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                <button type="submit" class="btn btn-primary ms-3">Add</button>
                                            </div>
                                        </form>
                                    </div>
                                </div>
                                </div>
                            </div>
                        </div>
                    </div>

Also there is screen of table: enter image description here

I`ve tried this, but id didnt work:

document.addEventListener("DOMContentLoaded", function() {

      const exampleModal = document.getElementById('addModal')
      if (exampleModal) {
        exampleModal.addEventListener('show.bs.modal', event => {
          // Button that triggered the modal
          const button = event.relatedTarget
          // Extract info from data-bs-* attributes
          const recipient = button.getAttribute('data-bs-whatever')
          // If necessary, you could initiate an Ajax request here
          // and then do the updating in a callback.

          // Update the modal's content.
          const modalTitle = exampleModal.querySelector('.modal-title')
          const modalBodyInput = exampleModal.querySelector('submit')

          if(recipient == "add"){
            modalTitle.textContent = `Addd`
            modalBodyInput.textContent = 'Add'
          }
          else if(recipient == "edit"){
            modalTitle.textContent = `Editt`
            modalBodyInput.textContent = 'Edit'
          }
        })
      }

      document.getElementById("addForm").addEventListener("submit", function(event) {
    event.preventDefault(); // Зупинка стандартної поведінки форми

    // Отримання значень полів форми
    var group = document.getElementById("group").value;
    var fname = document.getElementById("fname").value;
    var lname = document.getElementById("lname").value;
    var gender = document.getElementById("gender").value;
    var birthday = document.getElementById("birthday").value;
    var statusSw = document.getElementById("statusSw").checked;

    if (group == 0 || gender == 0){
        alert("Please select valid options for gender and group before clearing the form.");
        return;
    }

    var fullName = fname + " " + lname;

    // Перевірка, чи вибрано рядок для редагування
    var selectedRow = document.querySelector('tr.selected');
    if (selectedRow) {
        // Редагування вибраного рядка
        selectedRow.cells[1].textContent = group;
        selectedRow.cells[2].textContent = fullName;
        selectedRow.cells[3].textContent = gender;
        selectedRow.cells[4].textContent = birthday;
        selectedRow.cells[5].innerHTML = statusSw ? '<span class="status-dot status-dot-active"></span>' : '<span class="status-dot"></span>';
        selectedRow.classList.remove('selected'); // Видалення класу "selected"
        return;
    }

    // Створення елементів td для кожного значення
    var groupCell = document.createElement("td");
    groupCell.textContent = group;
    var nameCell = document.createElement("td");
    nameCell.textContent = fullName;
    var genderCell = document.createElement("td");
    genderCell.textContent = gender;
    var birthdayCell = document.createElement("td");
    birthdayCell.textContent = birthday;
    var statusCell = document.createElement("td");
    statusCell.innerHTML = statusSw ? '<span class="status-dot status-dot-active"></span>' : '<span class="status-dot"></span>';
    var checkboxCell = document.createElement("td");
    checkboxCell.innerHTML = '<input type="checkbox">';
    var optionsCell = document.createElement("td");
    optionsCell.innerHTML = '<button class="editBtn rounded-4" data-bs-toggle="modal" data-bs-target="#addModal" data-bs-whatever="edit" style="margin-right: 4px;"><i class="fa-solid fa-pencil"></i></button><button class="delBtn rounded-4"><i class="fa-solid fa-xmark"></i></button>';

    // Створення нового рядка та додавання до нього всіх стовпців
    var newRow = document.createElement("tr");
    newRow.appendChild(checkboxCell);
    newRow.appendChild(groupCell);
    newRow.appendChild(nameCell);
    newRow.appendChild(genderCell);
    newRow.appendChild(birthdayCell);
    newRow.appendChild(statusCell);
    newRow.appendChild(optionsCell);

    // Додавання обробника подій для кнопки "Видалити"
    var deleteButton = optionsCell.querySelector('.delBtn');
    deleteButton.addEventListener('click', function() {
        deleteRow(newRow);
    });

    // Додавання обробника подій для кнопки "Редагувати"
    var editButton = optionsCell.querySelector('.editBtn');
    editButton.addEventListener('click', function() {
        editRow(newRow);
    });

    // Додавання нового рядка до таблиці
    var userList = document.getElementById("stList");
    userList.appendChild(newRow);

    // Очищення полів форми
    document.getElementById("group").value = "0";
    document.getElementById("fname").value = "";
    document.getElementById("lname").value = "";
    document.getElementById("gender").value = "0";
    document.getElementById("birthday").value = "";
    document.getElementById("statusSw").checked = false;

    // Закриття модального вікна
    var addModal = new bootstrap.Modal(document.getElementById("addModal"));
    addModal.hide();
});

// Функція для редагування вибраного рядка
function editRow(row) {
    // Встановлення класу "selected" для вибраного рядка
    var selectedRow = document.querySelector('tr.selected');
    if (selectedRow) {
        selectedRow.classList.remove('selected');
    }
    row.classList.add('selected');

    // Заповнення полів форми даними вибраного рядка
    document.getElementById("group").value = row.cells[1].textContent;
    var fullName = row.cells[2].textContent.split(" ");
    document.getElementById("fname").value = fullName[0];
    document.getElementById("lname").value = fullName[1];
    document.getElementById("gender").value = row.cells[3].textContent;
    document.getElementById("birthday").value = row.cells[4].textContent;
    document.getElementById("statusSw").checked = row.cells[5].querySelector('.status-dot').classList.contains('status-dot-active');

    // Відобразити модальне вікно
    var addModal = new bootstrap.Modal(document.getElementById("addModal"));
    addModal.show();

    // Оновлення заголовку та вмісту кнопки в модальному вікні
    var modalTitle = document.getElementById("exampleModalLabel");
    var modalSubmitButton = document.getElementById("modalSubmitButton");
    modalTitle.textContent = "Edit Record";
    modalSubmitButton.textContent = "Save Changes";
}

// Функція для видалення рядка
function deleteRow(row) {
    row.parentNode.removeChild(row);
}

// Обробка закриття модального вікна
document.getElementById("addModal").addEventListener('hidden.bs.modal', function () {
    var selectedRow = document.querySelector('tr.selected');
    if (selectedRow) {
        selectedRow.classList.remove('selected');
    }
});


});
0

There are 0 best solutions below