Sunday, October 16, 2011

jQuery UI dialog without any close option

We use jQuery UI for designing web pages in out project. Some times back we had a scenario where the user log in to a dashboard was implemented using jQuery UI dialog (modal) component. Requirement was that the dashboard page should not be reached without passing the authentication process. But the dialog component of jQuery UI library provides a default X icon at the top left corner of the element which provides an option to close the dialog.

In our case, we wanted to reload the same page on click of the X icon. So that the user can not escape the login dialog by using the X icon. We achieved this by writing the page reload code inside dialog's close handler.  Everything worked fine until we had to handle the successful log in. Once user login succeeds we need to call dialog widget's close handler which reloads the page in turn. Because of this, even after a successful login, user gets the login dialog again.

The only way to stop this was, to remove the page reload code from the widget's close handler. Then it would require to remove the X icon from the dialog widget so that the close handler can not be invoked by clicking the X icon. But jQuery UI gives no option to build a dialog without close icon.

Thanks to Deepti Sharma for finding out a easy solution to the problem. Here is how it looks after the modification -


Below is the HTML code for creation of the dialog box.
<div id="login_div" title="Login" style="display:none;">
  <form id="login_form" name="login_form" action="LoginServlet?action=login" method="post">
   <table>
   <tbody>
    <tr>
     <td>Username: </td>
     <td><input type="text" name="username" id="username" size="20"></td>
    </tr>
    <tr>
     <td >Password:</td>
     <td><input type="password" name="password" id="password" size="20"></td>
    </tr>
   </tbody>
   </table>
  </form>
</div>


The JavaScript part of code is doing the actual business. First we create the login dialog using jQuery UI API, then we hide the X icon by setting its display property. Here is the code
$( "#login_div" ).dialog({
  autoOpen: false,
  height: 'auto',
  width: 400,
  modal: true,
  buttons: {
  "Submit": function() {
                  // form submission code goes here
  },
  "close": function() {
                  // close handler
  }
});

var dialogDivId = "login_div";

$('div[aria-labelledby="ui-dialog-title-'+ dialogDivId +'"] .ui-dialog-titlebar-close').css("display","none");



The important part is the aria-labelledby attribute. It will contain the original div id of the dialog. So, we can find out the correct X icon to hide (there are multiple dialog boxes in the page). Though the code looks dirty, it works.
Once the close icon is removed, user can only submit the login page but can't close/cancel the login.