Search code examples
javascriptruby-on-railssweetalertsweetalert2

sweet alert 2 gem confirm box redirect to link after pressing ok


I am not sure why ok or cancel doesnt do anything, anyways I want when someone press at ok to redirect it to a link

<div class="popup" onclick="sweetalertclick()">
              <p id="center"><%= image_tag "pickup.png" ,width: "80px"%><br>
                <span  onclick="sweetalertclick()"></span>Request a DDS pick u
                </span>
              </p>
            </div>
    <script>
    function sweetalertclick() {
    
    swal({
        title: "Request a DDS",
        text: "Please log in to DDS website to request a pick up, my code is: xxxx. By pressing ok you will link to google.com",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Ok",
        cancelButtonText: "Cancel",
        closeOnConfirm: false,
        closeOnCancel: false,
      },
      function(isConfirm){
        if (isConfirm) {
          window.location.href = "google.com"
        }
      }
    );
      
    }
    </script>

in gem file

gem 'rails-assets-sweetalert2', source: 'https://rails-assets.org'
gem 'sweet-alert2-rails'
gem 'sweet-alert-confirm'

in application.js

//= require sweetalert2
//= require jquery
//= require jquery_ujs
//= require sweet-alert2-rails
//= require cocoon 
//= require sweet-alert-confirm  
//= require_tree .

in application.scss

 *= require_self
 *= require sweetalert2
 *= require_tree .
 */

Solution

  • You have to use .then() and then pass the redirection procedure inside that:

    Example:

    function sweetalertclick() {
    
    swal({
        title: 'Request a DDS',
        text: "Please log in to DDS website to request a pick up, my code is: xxxx. By pressing ok you will link to google.com",
        showCancelButton: true,
        confirmButtonColor: "#DD6B55",
        confirmButtonText: "Ok",
      }).then((result) => {
      console.log(result)
        if (result) {
          window.location.href = "google.com";
        }
      });
      
    }