Search code examples
javascripthtmlsweetalertsweetalert2

Use Javascript if function to display a SweetAlert popup


I would like to display a SweetAlert popup if uploads are currently switched off, this is set by the li element having a class of "upload-off"

How can I incorporate an if Javascript condition to display the popup and just do nothing if the "upload-on" class if present of the <li>

I plan to use Vue on the page at a later date, so preferably need to use Javascript rather than jQuery (as I here of potential conflicts with Vue and jQuery)

<!-- There are two classes which toggle, upload-off and upload-on-->
<li class="uploadli upload-off">
    <p>Upload Off</p>
</li>

<input value="" id="myuploadbutton" type="file" name="Uploader" placeholder="Upload here">

<!-- Sweetalert Popup - Only display popup if uploads are currently disabled



function upload_check() {
swal({
    text: "Uploads are currently disabled, please apply here at http://www.example.com/apply",
    icon: "error",
    buttons: ['Apply Now'],
    dangerMode: true
    })
    .then(function(value) {
    console.log('returned value:', value);
    });
}

-->

OVERVIEW: User click on upload button, if the class "upload-off" is present on the <li> element we get a SweetAlert popup

Here is a similar SweetAlert issue

How to show SweetAlert in JavaScript


Solution

  • So check to see if the element exists

    document.querySelector("#myuploadbutton")
      .addEventListener('click', function(evt) {
        var li = document.querySelector('li.uploadli.upload-off');
        if (li) {
          evt.preventDefault()
          swal({
            text: "Uploads are currently disabled, please apply here at http://www.example.com/apply",
            icon: "error",
            buttons: ['cancel', 'Apply Now'],
            dangerMode: true
          }).then(function(value) {
            console.log('returned value:', value);
            if (value) {
              // window.location.href = "//www.example.com/apply"
            }
          });
        }
      })
    <script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
    <ul>
      <li class="uploadli upload-off">
        <p>Upload Off</p>
      </li>
    </ul>
    
    <input value="" id="myuploadbutton" type="file" name="Uploader" placeholder="Upload here">