Skip to content

NimTechnology

Trình bày các công nghệ CLOUD một cách dễ hiểu.

  • Kubernetes & Container
    • Docker
    • Kubernetes
      • Ingress
      • Pod
    • Helm Chart
    • OAuth2 Proxy
    • Isito-EnvoyFilter
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Vault
    • Longhorn – Storage
    • VictoriaMetrics
    • MetalLB
    • Kong Gateway
  • CI/CD
    • ArgoCD
    • ArgoWorkflows
    • Argo Events
    • Spinnaker
    • Jenkins
    • Harbor
    • TeamCity
    • Git
      • Bitbucket
  • Coding
    • DevSecOps
    • Terraform
      • GCP – Google Cloud
      • AWS – Amazon Web Service
      • Azure Cloud
    • Golang
    • Laravel
    • Python
    • Jquery & JavaScript
    • Selenium
  • Log, Monitor & Tracing
    • DataDog
    • Prometheus
    • Grafana
    • ELK
      • Kibana
      • Logstash
  • BareMetal
    • NextCloud
  • Toggle search form

[sweetalert2] Utilize SweetAlert2 to add an additional popup to your website.

Posted on November 15, 2024November 18, 2024 By nim No Comments on [sweetalert2] Utilize SweetAlert2 to add an additional popup to your website.

Đầu tiên mình có 1 table như sau:

Mình mong muốn là khi ấn vào edit nó hiện 1 popup để người dùng chỉnh min của hệ thống.

<table class="table table-flush dataTable-table" id="datatable-search">
    <thead class="thead-light">
        <tr>
            <th data-sortable="" style="width: 28.2309%;"><a href="#" class="dataTable-sorter">ScaleObject</a></th>
            <th data-sortable="" style="width: 29.4228%;"><a href="#" class="dataTable-sorter">Deployment</a></th>
            <th data-sortable="" style="width: 12.4843%;"><a href="#" class="dataTable-sorter">Status</a></th>
            <th data-sortable="" style="width: 7.59097%;"><a href="#" class="dataTable-sorter">Min</a></th>
            <th data-sortable="" style="width: 8.09285%;"><a href="#" class="dataTable-sorter">Max</a></th>
            <th data-sortable="" style="width: 14.1782%;"><a href="#" class="dataTable-sorter">Action</a></th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>
                <div class="d-flex align-items-center">
                    <p id="customCheck1" class="text-xs font-weight-normal ms-2 mb-0">archive-bitdefender-scaledobject</p>
                </div>
            </td>
            <td class="font-weight-normal">
                <h6 class="ms-3 my-auto">eng-archive-bitdefender</h6>
            </td>
            <td class="text-xs font-weight-normal">
                <div class="d-flex align-items-center">
                    <button class="btn btn-icon-only btn-rounded btn-outline-success mb-0 me-2 btn-sm d-flex align-items-center justify-content-center">
                        <i class="material-symbols-rounded text-sm" aria-hidden="true">done</i>
                    </button>
                    <span>ready</span>
                </div>
            </td>
            <td class="text-sm font-weight-normal">
                2
            </td>
            <td class="text-sm font-weight-normal">
                2
            </td>
            <td class="text-xs font-weight-normal">
                <a class="btn btn-link text-dark px-3 mb-0" href="javascript:;"><i class="material-symbols-rounded text-sm me-2">edit</i>Edit</a>
            </td>
        </tr>
    </tbody>
</table>

document.addEventListener("DOMContentLoaded", () => {
    document.querySelectorAll(".btn-link").forEach((editButton) => {
        editButton.addEventListener("click", function () {
            // Your code here
        });
    });
});

document.addEventListener("DOMContentLoaded", () => { … });

This means: “Wait until the web page has fully loaded (HTML is ready to work with) before running this code.”
This ensures that all the elements (like buttons) exist in the page before the script tries to find and interact with them.

document.querySelectorAll(".btn-link")

This means: “Find all elements in the page that have the class btn-link.”
It collects all the “Edit” buttons in the table (or elsewhere) into a list (like a group of items).

.forEach((editButton) => { … });

This means: “Go through each button in the list one by one.”
For every editButton, it runs the function provided inside the { … }.

editButton.addEventListener("click", function () { … });

This means: “When someone clicks this specific editButton, run the code inside the { … }.”
It attaches a “click listener” to each button, so it knows what to do when clicked.

function () { … }

This is the actual code that runs when someone clicks the button.
Inside this function, you can write any code to define what happens when the Edit button is clicked (e.g., show a popup, send data, etc.).

        <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
        <script>
          // Attach an event listener to the Edit button
          document.addEventListener("DOMContentLoaded", () => {
            document.querySelectorAll(".btn-link").forEach((editButton) => {
              editButton.addEventListener("click", function () {
                // Get the product ID from the row
                const productRow = this.closest("tr");
                const scaleOject = productRow.querySelector("p.text-xs").textContent.trim(); // e.g., "#10421"
                // Get the environment from the card header (using the ID)
                var environment = $('#k8s-environment').text().trim();

                // Split the string by space and take the first word
                var environment = environment.split(' ')[0].toLowerCase();

                // SweetAlert2 for input
                Swal.fire({
                  title: "Edit Product Minimum Value",
                  html: `
                    <p>Editing Product ID: <strong>${scaleOject}</strong></p>
                    <label for="minValueInput">Enter Minimum Value:</label>
                    <input id="minValueInput" type="number" class="swal2-input" min="0" placeholder="Enter minimum value" />
                    <label for="retentionPeriod">Retention period (days):</label>
                    <input id="retentionPeriod" type="number" class="swal2-input" value="1" placeholder="Enter minimum value" />
                  `,
                  showCancelButton: true,
                  confirmButtonText: "Submit",
                  preConfirm: () => {
                    const minValue = document.getElementById("minValueInput").value;
                    const retentionPeriod = document.getElementById("retentionPeriod").value;

                    // Validate inputs
                    if (!minValue || minValue < 0) {
                      Swal.showValidationMessage("Please enter a valid number greater than or equal to 0");
                    }
                    if (!retentionPeriod || retentionPeriod < 1) {
                      Swal.showValidationMessage("Please enter a valid number greater than or equal to 1");
                    }

                    // Return validated values
                    return { minValue, retentionPeriod };
                  }
                }).then((result) => {
                  if (result.isConfirmed) {
                    const { minValue, retentionPeriod } = result.value;

                    // Use AJAX to send the data
                    $.ajax({
                      url: "{{asset('/update-min-max-scale-object')}}",
                      type: "POST",
                      data: {
                        _token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'), // Laravel CSRF token
                        scaleOject: scaleOject,
                        minValue: minValue,
                        environment: environment,
                        retentionPeriod: retentionPeriod
                      },
                      success: function (data) {
                        console.log('Success:', data);
                        // Reload the page
                        location.reload();
                        // Optionally, update the UI or show a success message
                        Swal.fire({
                          icon: 'success',
                          title: 'Success',
                          text: 'Minimum value updated successfully!'
                        });
                      },
                      error: function (error) {
                        console.error('Error:', error);
                        // Handle errors, e.g., display an error message
                        Swal.fire({
                          icon: 'error',
                          title: 'Oops...',
                          text: 'Something went wrong!'
                        });
                      }
                    });
                  }
                });
              });
            });
          });
        </script>

tiếp theo bạn cần tạo popup thông qua việc custom HTML

                // SweetAlert2 for input
                Swal.fire({
                  title: "Edit Product Minimum Value",
                  html: `
                    <p>Editing Product ID: <strong>${scaleOject}</strong></p>
                    <label for="minValueInput">Enter Minimum Value:</label>
                    <input id="minValueInput" type="number" class="swal2-input" min="0" placeholder="Enter minimum value" />
                    <label for="retentionPeriod">Retention period (days):</label>
                    <input id="retentionPeriod" type="number" class="swal2-input" value="1" placeholder="Enter minimum value" />
                  `,
                  showCancelButton: true,
                  confirmButtonText: "Submit",

Lúc này sẽ có 1 function preConfirm để assess các Input đã đặt được các requirement hay chưa như là không được để trống hoặc lớn hơn 1

                  preConfirm: () => {
                    const minValue = document.getElementById("minValueInput").value;
                    const retentionPeriod = document.getElementById("retentionPeriod").value;

                    // Validate inputs
                    if (!minValue || minValue < 0) {
                      Swal.showValidationMessage("Please enter a valid number greater than or equal to 0");
                    }
                    if (!retentionPeriod || retentionPeriod < 1) {
                      Swal.showValidationMessage("Please enter a valid number greater than or equal to 1");
                    }

                    // Return validated values
                    return { minValue, retentionPeriod };
                  }

If any of these conditions fail, an error message is shown using Swal.showValidationMessage() and the process stops.

If both inputs are valid, the code returns the values of minValue and retentionPeriod as an object: { minValue, retentionPeriod }.

Tiếp theo là tiếp nhận input và gửi đi:

                }).then((result) => {
                  if (result.isConfirmed) {
                    const { minValue, retentionPeriod } = result.value;

                    // Use AJAX to send the data
                    $.ajax({
                      url: "{{asset('/update-min-max-scale-object')}}",
                      type: "POST",
                      data: {
                        _token: document.querySelector('meta[name="csrf-token"]').getAttribute('content'), // Laravel CSRF token
                        scaleOject: scaleOject,
                        minValue: minValue,
                        environment: environment,
                        retentionPeriod: retentionPeriod
                      },
                      success: function (data) {
                        console.log('Success:', data);
                        // Reload the page
                        location.reload();
                        // Optionally, update the UI or show a success message
                        Swal.fire({
                          icon: 'success',
                          title: 'Success',
                          text: 'Minimum value updated successfully!'
                        });
                      },
                      error: function (error) {
                        console.error('Error:', error);
                        // Handle errors, e.g., display an error message
                        Swal.fire({
                          icon: 'error',
                          title: 'Oops...',
                          text: 'Something went wrong!'
                        });
                      }
                    });
                  }
                });
              });
            });
          });
        </script>
  1. Check Confirmation:
    The if (result.isConfirmed) part ensures that the user actually clicked the “Submit” button in the popup. If not, it does nothing.
  2. Extract Input Values:
    The inputs minValue and retentionPeriod entered by the user are retrieved from result.value.
  3. Send Data to the Server (AJAX):
    – AJAX is used to send the data to the server without refreshing the page.
    – The data sent includes:
    + scaleObject: The ID of the product being edited.
    + minValue: The minimum value entered by the user.
    + retentionPeriod: The retention period entered by the user.
    + environment: The environment (e.g., development, production).
    + _token: A CSRF token to ensure the request is secure (required by Laravel).
  4. Handle the Response from the Server:
    – If successful (success):
    + A success message is displayed to the user using SweetAlert2.
    + The page is reloaded to show the updated information.
    – If an error occurs (error):
    + An error message is displayed, indicating something went wrong.
Laravel

Post navigation

Previous Post: [Git] Check out the git-low application for your releases.
Next Post: [Laravel] How to implement the schedule in Docker Laravel.

More Related Articles

[Laravel] How to implement the schedule in Docker Laravel. Laravel
[PHP] Hướng dẫn kiểm tra array rỗng hay null không? Laravel
[Laravel] How to Route to Controller to View on Laravel 8 + Laravel
[php-laravel] Handle a new project laravel. Laravel
[Laravel] This form is not secure. Autofill has been turned off Laravel
[Popup/Ajax] Tạo popup(modal/bootstrap) insert data bằng ajax và php Coding

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Tham Gia Group DevOps nhé!
Để Nim có nhiều động lực ra nhiều bài viết.
Để nhận được những thông báo mới nhất.

Recent Posts

  • [Argo Workflow] Create an access token for Argo Workflows July 14, 2025
  • [Argo Workflow] SSO Authentication for Argo Workflows. July 14, 2025
  • [AWS/EKS] Cache Docker image to accelerate EKS container deployment. July 10, 2025
  • [Laravel] Laravel Helpful June 26, 2025
  • [VScode] Hướng dẫn điều chỉnh font cho terminal June 20, 2025

Archives

  • July 2025
  • June 2025
  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • October 2024
  • September 2024
  • August 2024
  • July 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • April 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • June 2021

Categories

  • BareMetal
    • NextCloud
  • CI/CD
    • Argo Events
    • ArgoCD
    • ArgoWorkflows
    • Git
      • Bitbucket
    • Harbor
    • Jenkins
    • Spinnaker
    • TeamCity
  • Coding
    • DevSecOps
    • Golang
    • Jquery & JavaScript
    • Laravel
    • NextJS 14 & ReactJS & Type Script
    • Python
    • Selenium
    • Terraform
      • AWS – Amazon Web Service
      • Azure Cloud
      • GCP – Google Cloud
  • Kubernetes & Container
    • Apache Kafka
      • Kafka
      • Kafka Connect
      • Lenses
    • Docker
    • Helm Chart
    • Isito-EnvoyFilter
    • Kong Gateway
    • Kubernetes
      • Ingress
      • Pod
    • Longhorn – Storage
    • MetalLB
    • OAuth2 Proxy
    • Vault
    • VictoriaMetrics
  • Log, Monitor & Tracing
    • DataDog
    • ELK
      • Kibana
      • Logstash
    • Fluent
    • Grafana
    • Prometheus
  • Uncategorized
  • Admin

Copyright © 2025 NimTechnology.