javascriptjquerysweetalertsweetalert2

How can I enable Confirm Button on input in sweet alert 2


I need to disable the confirm button when the user hasn't changed any value in the text box inside the sweet alert and enable it only when the value in the text box has changed but I can't seem to find a way for this. here's my code:

swal({
            title: 'Please Enter Page Name',
            input: 'text',
            inputValue: PageName,
            confirmButtonText: 'Save',
            onOpen: function (){
                swal.disableConfirmButton(); //this disables the button
            }
            preConfirm: function (Name) {
                return new Promise(function (resolve, reject) {
                    resolve();
                })
            },
            allowOutsideClick: false
        })

I used onOpen to fire the swal.disableConfirmButton(); method but I don't know where to use swal.enableConfirmButton();. is there any function like onInput or something similar? If yes how to use that to achieve the desired result?

here's a codepen of what I have achieved so far.

https://codepen.io/zeeshanadilbutt/pen/NLvmZz?editors=0010


Solution

  • Since there is no onInput or something similar for input: text, you can use getInput inside onOpen and add an event listener to that to enable or disable your button accordingly.

    Check the working snippet.

    swal({
      input: 'text',
      onOpen: function () {
        swal.disableConfirmButton();
        swal.getInput().addEventListener('keyup', function(e) {
          if(e.target.value === '') {
            swal.disableConfirmButton();
          } else {
            swal.enableConfirmButton();
          }
        })
      }
    });
      <script src="https://unpkg.com/sweetalert2"></script>