5

I have been trying for more than two days to run SweetAlert prompt in a modal bootstrap without success, the input is not accessible and I don't understand why. I need help please.

$("#openSWAL").click(function(){
 swal({
    title: "An input!",
    text: "Write something interesting:",
    type: "input",
    showCancelButton: true,
    closeOnConfirm: false,
    animation: "slide-from-top",
    inputPlaceholder: "Write something"
  },
       function(inputValue){
    if (inputValue === false) return false;

    if (inputValue === "") {
      swal.showInputError("You need to write something!");
      return false
    }

    swal("Nice!", "You wrote: " + inputValue, "success");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Open modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>
      </div>
      <div class="modal-body">
        Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    Bla<br/>
    
      </div>
      <div class="modal-footer">
        <button type="button" id="openSWAL" class="btn btn-warning">Open SweetAlert prompt</button>
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>
      </div>
    </div>
  </div>
</div>
Manfred Radlwimmer
  • 13,257
  • 13
  • 53
  • 62
Mathias Martin
  • 63
  • 1
  • 1
  • 3

7 Answers7

18

Removing tabindex="-1" from myModal seems to do the job: Fiddle

The problem is tabindex, because if you set it to -1, you won't be able to access that element. More info here, and in this question.

Community
  • 1
  • 1
lch
  • 2,028
  • 2
  • 25
  • 46
2

Bootstrap modal has z-index=10001 in general. But Sweetalert modal has z-index=10000 or something less than bootstrap modal's z-index. So its always appear behind of bootstrap modal.

Give your SweetAlert modal higher z-index than bootstrap modal. Problem will be solved.

In my case, it works perfectly. I am using sweetalert: ^2.1.2

.swall-overlay {
    z-index: 100005;
}
.swal-modal {
    z-index: 99999;
}

Please remember, don't try to change bootstrap modal z-index. Its a common scenario that Alert always appear on top of everything, even on top of modal. So, its a good practice changing sweetalert z-index.

Robin
  • 4,902
  • 2
  • 27
  • 43
0

We send back JSON error object on error and show that in a SWAL popup. The problem is that the user can't select text.

The problem seems to be in the tabindex html attribute. We're removing it with the didRender event (formally onRender in older versions of sweetalert2).

(we're using limonte-sweetalert2@10.3.5 via cdnjs)

   $.ajax({ /* stuff */
   }).fail(function(result) {
        var data = $.parseJSON(result.responseText);

        var text = 'Something went wrong!';
        if (data && data.hasOwnProperty('message')) {
            text = '<div class="swal2-error-message">' + data.message + '</div>';
        }

        Swal.fire({
            icon: 'error',
            title: 'Encountered the following exception',
            html: text,
            width: 850,
            // swal is broken by design, this will allow you to select text in the above error div.
            didRender: function(x) { $(".swal2-popup.swal2-modal").removeAttr("tabindex"); }
        });
    })
BurnsBA
  • 4,347
  • 27
  • 39
0

Hope all is well, I faced a similar issue where i am calling bootstrap modal popup and in that popup i am take input from user with swal alert. problem which i face was that i was not able to enter any thing in the swal input box. This was because of the modal background shield which was overlayer over the swal alert hence preventing me from using the swal alert. my solution was simple i hide the modal background shield and when i am done with the swal alert i reshow it. Ok I am using it on asp.net mvc .

bootstap Modal

//                              |   
//                              \/     
<div class="modal fade" id="UpdateModal" tabindex="-1" aria-labelledby="UpdateModalLabel" aria-hidden="true">
    <div id="GradeWiseViewModal" class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content">
           
            <div class="modal-body" id="modal-body">

            </div>
            
        </div>
    </div>
</div>

the div with id= UpdateModal was overlaying over the swal alert so i need to remove it and bring it back so i dont lose any data in the process. so the function which was calling the swal alert given below need to be modified.

<script>
function abc(a,b,c) {
       
         $('#UpdateModal').hide();
         swal({
             text: 'Please Provide value\'s Label',
             content: "input",
             button: {
                 text: "Add value",
                 closeModal: true,
             },
         })
     .then(head => {
         if (!head) throw null;
         $.ajax({
             url: "/address/actionresult",
             cache: false,
             type: 'Post',
             data: { 'a': a, 'b': b, 'c': c },
             success: function (res) {
                 OpenModal(sid, gid, bid, 'DSCollapse');
                 $('#UpdateModal').show();
             }
         });
     })
         .catch(err => {
             if (err) {
                 swal("Oh noes!", "The AJAX request failed!", "error");
             } else {
                 swal.stopLoading();
                 swal.close();
                 $('#UpdateModal').show();
             }
         });
        // $('#UpdateModal').show();  //<==== this is a no no... 
     }
</script>

When the function is called abc(1,2,3) it will hide the overlaying div $('#UpdateModal').hide(); and once the swal alert does it job and send the data, upon the success of the call we show MODAL $('#UpdateModal').show();

SO IN SHORT

$('#UpdateModal').hide()  <-----------------------------------
SWAL({}).THEN({ 
AJAX ({ 
       success:FUNCITON(){ 
                         $('#UpdateModal').SHOW()  <----------
         } 
       }); 
  });

REMEMBER NOT A SOLUTION, JUST A FIX.
Hopes this clears you headache.

Ad Kahn
  • 551
  • 4
  • 6
-1

You can usually solve bootstrap modal focus issues by disabling the focus enforcement using $.fn.modal.Constructor.prototype.enforceFocus = function () {};

Zoren Konte
  • 306
  • 4
  • 12
-1

Put this line in your first modal

$(document).off('focusin.modal');
Hoang Tran
  • 886
  • 3
  • 13
  • 32
-2

I hope the following codes will help you. :)

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.js"></script>
</head>

<body>
    <!-- Button trigger modal -->
    <button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
        Open modal
    </button>
    <!-- End of button trigger modal -->
    <!-- Modal -->
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel">Modal title</h4>
                </div>
                <div class="modal-body">                    
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-warning" onclick="adddata()">Add</button>
                    <button type="button" class="btn btn-default" onclick="modalclose()">Close</button>
                    <button type="button" class="btn btn-primary" onclick="savechanges()">Save changes</button>
                </div>
            </div>
        </div>
    </div>
</body>

</html>
<script type="text/javascript">
function adddata() {
    $('#myModal').modal('hide');
    swal({
        title: "An input!",
        text: "Write something interesting:",
        type: "input",
        showCancelButton: true,
        closeOnConfirm: false,
        inputPlaceholder: "Write something"
    }, function(inputValue) {
        if (inputValue === false) return false;
        if (inputValue === "") {
            swal.showInputError("You need to write something!");
            return false
        }
        swal("Nice!", "You wrote: " + inputValue, "success");
    });
}

function modalclose() {
    swal({
            title: "Are you sure you want to exit?",
            text: "You will not be able to save and recover this imaginary file!",
            type: "warning",
            showCancelButton: true,
            confirmButtonClass: "btn-danger",
            confirmButtonText: "Yes, I'm going out!",
            cancelButtonText: "No, I'm stay!",
            closeOnConfirm: false,
            closeOnCancel: false
        },
        function(isConfirm) {
            if (isConfirm) {
                swal("Goodbye!", "Your imaginary file has not been save.", "success");
                $('#myModal').modal('hide');
            } else {
                swal("Cancelled", "Your imaginary file is safe :)", "error");
            }
        });
}

function savechanges() {
    $('#myModal').modal('hide');
    swal("Good job!", "Your imaginary file has been successfully save!", "success");
}
</script>

This is also available of my JSFiddle account.

Carl Angelo Nievarez
  • 573
  • 1
  • 11
  • 33