2

Использую библиотеку для диалоговых окон SweetAlert2 https://sweetalert2.github.io/

Мой код, где пользователь вводит значения в поля:

swal({
      title: '<h2>' + add_alb_title  + '</h2>',
      type: 'info',
      html:
        '<div class="swal_title">' + album_title + '</div><input type="text" value="" class="album_title" name="album_title" maxlength="30" /><br />' +
        '<div class="swal_title">' + album_description + '</div><textarea name="album_description" class="album_description" rows="4" cols="50" maxlength="125" ></textarea><br />' +
        '',
      showCloseButton: true,
      showCancelButton: true,
      confirmButtonText: button_add,
      cancelButtonText: button_cancel
    }).then(function (result) {
    // Здесь нужно получить значения из полей, чтобы отправить их в ajax
    // В result просто true
      swal(
        'Created!',
        'Your album has been created.' + JSON.stringify(result),
        'success'
      )
    });

Подскажите, как получить значения input и textarea?

1 ответ 1

2

В then() это делать поздно, т.к. модальное окно там уже закрыто и его контент потерян.

preConfirm()- правильное место для того, чтобы получить значения кастомных полей ввода. Также, советую использовать документированный метод swal.getContent() для получения содержимого:

Swal.fire({
  html:
    '<input name="album_title"><br>' +
    '<textarea name="album_description" rows="4" cols="50"></textarea>',
  preConfirm: () => {
    var album_title = swal.getContent().querySelector('[name=album_title]').value
    var album_description = swal.getHtmlContainer().querySelector('[name=album_description]').value
    
    console.log(album_title, album_description)
    
    // тут делаешь AJAX запрос
  },
  showLoaderOnConfirm: true
})
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.