Learner
Learner

Reputation: 239

Bootstrap Issue With Modal

I've an issue with Bootstrap Modal when trying to show/hide it using code. When we enter text with more than 3 characters and press Enter once, the modal shows and then disappears as intended. However, if we keep on pressing Enter key, the screen turns black.

I've seen other posts with this issue and all of them suggest to use data-keyboard="false", but this doesn't work in my case. Could somebody please help?

UPDATE

The code snippet is now updated with working solution posted in answer.

$(document).ready(function(){

  $("#txtSearch").keydown(function(event){
    if($.trim($(this).val()) != "" && $(this).val().length > 3 && event.which == 13 ){
      showLoading();

      //Some Code
      hideLoading();
  }
  });
  
});

function showLoading(){
  if(!$('.modal-backdrop').is(':visible')){
    $("#myModal").modal("show");
  }
}

function hideLoading(){
  $("#myModal").modal("hide");
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<input id="txtSearch" />
<div id="myModal" class="modal fade" role="dialog" data-backdrop="static" data-keyboard="false">
<h1 style="color:white">Loading...</h1>
</div>

Upvotes: 1

Views: 80

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

Instead to use the global variable isLoading I suggest to test if the modal-backdrop is visible before opening the modal:

if (!$('.modal-backdrop').is(':visible')) {
    $("#myModal").modal("show");
    console.log('show');
}

The snippet:

$(document).ready(function () {
    $("#txtSearch").keydown(function (event) {
        if ($.trim($(this).val()) != "" && $(this).val().length > 3 && event.which == 13) {
            showLoading();
            setTimeout(function() {
                hideLoading();
            }, 1000);
            //Some Code
            //hideLoading();
        }
    });

});

function showLoading() {
    if (!$('.modal-backdrop').is(':visible')) {
        $("#myModal").modal("show");
        console.log('show');
    }
}

function hideLoading() {
    $("#myModal").modal("hide");
    console.log('hide');
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


<input id="txtSearch"/>

<div id="myModal" class="modal fade" role="dialog" data-backdrop="static" data-keyboard="false">
    <h1 style="color:white">Loading...</h1>
</div>

Upvotes: 1

Related Questions