Archive for category Bootstrap

Give focus to a control in a Bootstrap modal popup window

The times that try men’s’ souls is when you have a Bootstrap modal popup window, and you can’t get the control you want to get focus. So if I have a modal popup window like so:

<div id=”resultsModal” class=”modal fade” role=”dialog”>
   <div class=”modal-dialog”>
      <div class=”modal-content”>
         <div class=”modal-header”>
            <button id=”modalClose” type=”button” class=”close” data-dismiss=”modal”>&times;</button>
            <h4 class=”modal-title text-center”>Update Record</h4>
         </div>

         <div class=”modal-body”>
            <div class=”form-inline” style=”margin-left: auto; margin-right: auto; width: 400px”>
               <div class=”form-group”>
                  <label for=”theDate” >Date: </label>
                  <input type=”text” id=”theDate” class=”form-control” /><br>
                  <input type=”button” id=”save” value=”Save” onclick=”saveRecord() class=”form-control saveButton” />
               </div>
            </div>
         </div>

         <div class=”modal-footer”>
            <button type=”button” class=”btn btn-default” data-dismiss=”modal”>Cancel</button>
         </div>
      </div>
   </div>
</div>

To give focus to the date textbox, I use this little snippet:

$(“#myModal”).on(“shown.bs.modal”, function () {
     $(“#theDate”).focus();
})

 

Advertisements

Leave a comment

Bootstrap modal popup window persists

I had a problem with Bootstrap modal popup window not going away properly. I was returning search results in an MVC application, and if there were multiple results returned, the popup would be displayed. The modal popup was standard code you see on the Bootstrap web site, and I had a jQuery method to get results from a Web API call and, after a successful result, would close the popup by programmatically clicking the modalClose button:

function getEmpInfo(id) {
    var url = 'http://localhost:12345/api/EmpController/';

    $.ajax({
        url: url + '?id=' + id,
        type: 'GET',
        dataType: 'json',
        cache: false,
        success: function (d) {
            populateGeneralInfo(d);
            $("#modalClose").click();
        }
    });
}

As I said, if the getEmpInfo once, it would work, but more than once and the page would basically freeze – the entire screen would disabled. The popup window itself would disappear, but the page stayed dark.

After using the IE developer tools, I noticed that there was a modal DIV tag that was remaining, and that was causing the problem:


To resolve this, I modified the success callback of the getEmpInfo JS method, and added code to remove that recalcitrant DIV:

        success: function (d) {
            populateGeneralInfo(d);
            $("#modalClose").click();
            $('div[class*="modal-backdrop"]').remove();
        }

Leave a comment