😍Cách sử dụng jQuery trong sweetAlert2 là chúng ta phải sử dụng didOpen full (ok)

https://sweetalert2.github.io/recipe-gallery/timer-methods.html?utm_source=zalo&utm_medium=zalo&utm_campaign=zalo

Ngoài didOpen chúng ta có thể xem willOpen

1. Sử dụng với jQuery chúng ta sử dụng với didRender, preConfirm

preConfirm: () => {
 console.log($('#addField'))
},
didRender: () => {
 $('#addField').css('color','red');
},

C:\xampp8\htdocs\lva\index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
    let timerInterval;
    Swal.fire({
      title: 'Auto close alert!',
      html: `
      <div class="wrapper">
        Select :
        <select name="parent_selection" id="parent_selection">
          <option value="">-- Please Select --</option>
          <option value="continents">Continents</option>
          <option value="oceans">Oceans</option>
        </select>
        <select name="child_selection" id="child_selection" disabled></select>
      </div>`,
      didOpen: () => {
        const content = Swal.getHtmlContainer();
        const $ = content.querySelector.bind(content);
        const select = $('#mySelectElement');
        console.log(select);
      }
    }).then((result) => {
      console.log($("#parent_selection").find(':selected').val());
    });
  </script>
</body>
</html>

C:\xampp8\htdocs\lva\script.js

$(document).ready(function () {
  //create arrays to store option and values
  var continents = [{
    display: "Asia",
    value: "asia"
  },
  {
    display: "Africa",
    value: "africa"
  },
  {
    display: "Antarctica",
    value: "antarctica"
  },
  {
    display: "Australia",
    value: "australia"
  },
  {
    display: "Europe",
    value: "europe"
  },
  {
    display: "North America",
    value: "north-america"
  },
  {
    display: "South America",
    value: "south-america"
  }
  ];
  var oceans = [{
    display: "Pacific",
    value: "pacific"
  },
  {
    display: "Atlantic",
    value: "atlantic"
  },
  {
    display: "Indian",
    value: "indian"
  },
  {
    display: "Southern",
    value: "southern"
  },
  {
    display: "Arctic",
    value: "arctic"
  }
  ];
  //If parent option is changed
  $("#parent_selection").change(function () {
    var parent = $(this).val(); //get option value from parent
    switch (parent) { //using switch compare selected option and populate child
      case 'continents':
        $('#child_selection').attr('disabled', false);
        list(continents);
        break;
      case 'oceans':
        $('#child_selection').attr('disabled', false);
        list(oceans);
        break;
      default: //default child option is blank
        $("#child_selection").html('');
        $('#child_selection').attr("disabled", true);
        break;
    }
  });
  //function to populate child select box
  function list(array_list) {
    $("#child_selection").html(""); //reset child options
    $(array_list).each(function (i) { //populate child options
      $("#child_selection").append("<option value='" + array_list[i].value + "'>" + array_list[i].display + "</option>");
    });
  }
});

2. Lấy giá trị

Ngoài cách 1. ở trên sử dụng didOpen thì còn có cách sử dụng preConfirm

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
    let timerInterval;
    Swal.fire({
      title: 'Auto close alert!',
      html: `
      <div class="wrapper">
        Select :
        <select name="parent_selection" id="parent_selection">
          <option value="">-- Please Select --</option>
          <option value="continents">Continents</option>
          <option value="oceans">Oceans</option>
        </select>
        <select name="child_selection" id="child_selection" disabled></select>
      </div>`,
      preConfirm: () => {
        const select = Swal.getPopup().querySelector('#parent_selection').value
        return { select}
      }
    }).then((result) => {
      Swal.fire(`
      Select: ${JSON.stringify(result)}
    `.trim())
    });
  </script>
</body>
</html>

3. Sử dụng third-patry

C:\xampp8\htdocs\lva\index.php

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.all.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/pikaday/css/pikaday.css">
  <script src="https://cdn.jsdelivr.net/npm/pikaday/pikaday.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
    let timerInterval;
    Swal.fire({
      title: 'Please enter departure date',
      input: 'text',
      inputValue: new Date().toISOString(),
      stopKeydownPropagation: false,
      preConfirm: () => {
        if (datepicker.getDate() < new Date(new Date().setHours(0, 0, 0, 0))) {
          Swal.showValidationMessage(`The departure date can't be in the past`)
        }
        return datepicker.getDate()
      },
      didOpen: () => {
        datepicker = new Pikaday({
          field: Swal.getInput()
        });
        setTimeout(() => datepicker.show(), 400); // show calendar after showing animation
      }
    }).then((result) => {
      console.log(result.value)
    })
  </script>
</body>
</html>

4. reCAPTCHA

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script src="https://www.google.com/recaptcha/api.js?onload=showSweetAlertRecaptcha"></script>
  <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
    function showSweetAlertRecaptcha() {
      Swal.fire({
        title: 'SweetAlert2 + Recaptcha',
        html: '<div id="recaptcha"></div>',
        willOpen: function() {
          grecaptcha.render('recaptcha', {
            'sitekey': '6Ld32_cjAAAAAFr7j8I4Jme1Z7JhxL3f_HSJ560E'
          });
        },
        preConfirm: function() {
          if (grecaptcha.getResponse().length === 0) {
            Swal.showValidationMessage(`Please verify that you're not a robot`)
          }
        }
      })
    }
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://www.google.com/recaptcha/api.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
    const inputValue = 345.67
    const inputStep = 0.01
    Swal.fire({
      title: 'input[number] + input[range]',
      html: `
    <input
      type="number"
      value="${inputValue}"
      step="${inputStep}"
      class="swal2-input"
      id="range-value">`,
      input: 'range',
      inputValue,
      inputAttributes: {
        min: 0,
        max: 1000,
        step: inputStep
      },
      didOpen: () => {
        const inputRange = Swal.getInput()
        const inputNumber = Swal.getHtmlContainer().querySelector('#range-value')
        // remove default output
        inputRange.nextElementSibling.style.display = 'none'
        inputRange.style.width = '100%'
        // sync input[type=number] with input[type=range]
        inputRange.addEventListener('input', () => {
          inputNumber.value = inputRange.value
        })
        // sync input[type=range] with input[type=number]
        inputNumber.addEventListener('change', () => {
          inputRange.value = inputNumber.value
        })
      }
    })
  </script>
</body>
</html>

6. Sidebar

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://www.google.com/recaptcha/api.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css"/>
  <title>Document</title>
  <style>
    select:empty {
      display: none !important;
    }
  </style>
</head>
<body>
  <script type="text/javascript">
     Swal.fire({
      title: 'Left sidebar 👋',
      position: 'top-start',
      showClass: {
        popup: `
      animate__animated
      animate__fadeInLeft
      animate__faster
    `
      },
      hideClass: {
        popup: `
      animate__animated
      animate__fadeOutLeft
      animate__faster
    `
      },
      grow: 'column',
      width: 300,
      showConfirmButton: false,
      showCloseButton: true
    })
  </script>
</body>
</html>

7. Toast

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://www.google.com/recaptcha/api.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
  <title>Document</title>
  <style>
    #custom-target {
      position: relative;
      width: 600px;
      height: 300px;
      border-style: solid;
    }
    .position-absolute {
      position: absolute !important;
    }
  </style>
</head>
<body>
  <div id="custom-target"></div>
  <script type="text/javascript">
    Swal.fire({
      text: 'Toast with custom target',
      target: '#custom-target',
      customClass: {
        container: 'position-absolute'
      },
      toast: true,
      position: 'bottom-right'
    })
  </script>
</body>
</html>

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
  <title>Document</title>
  <style>
  </style>
</head>
<body>
  <script type="text/javascript">
    let timerInterval
    Swal.fire({
      title: 'Auto close alert!',
      html: 'I will close in <b></b> milliseconds.',
      timer: 2000,
      timerProgressBar: true,
      didOpen: () => {
        Swal.showLoading()
        const b = Swal.getHtmlContainer().querySelector('b')
        timerInterval = setInterval(() => {
          b.textContent = Swal.getTimerLeft()
        }, 100)
      },
      willClose: () => {
        clearInterval(timerInterval)
      }
    }).then((result) => {
      /* Read more about handling dismissals below */
      if (result.dismiss === Swal.DismissReason.timer) {
        console.log('I was closed by the timer')
      }
    })
  </script>
</body>
</html>

9. Use API

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/sweetalert2@11.4.33/dist/sweetalert2.min.css">
  <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="script.js"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/4.1.1/animate.min.css" />
  <title>Document</title>
  <style>
  </style>
</head>
<body>
  <script type="text/javascript">
    Swal.fire({
      title: 'Submit your Github username',
      input: 'text',
      inputAttributes: {
        autocapitalize: 'off'
      },
      showCancelButton: true,
      confirmButtonText: 'Look up',
      showLoaderOnConfirm: true,
      preConfirm: (login) => {
        return fetch(`//api.github.com/users/${login}`)
          .then(response => {
            if (!response.ok) {
              throw new Error(response.statusText)
            }
            return response.json()
          })
          .catch(error => {
            Swal.showValidationMessage(
              `Request failed: ${error}`
            )
          })
      },
      allowOutsideClick: () => !Swal.isLoading()
    }).then((result) => {
      if (result.isConfirmed) {
        Swal.fire({
          title: `${result.value.login}'s avatar`,
          imageUrl: result.value.avatar_url
        })
      }
    })
  </script>
</body>
</html>

Last updated