Web Development Tips and Examples

Menu

ShowModalDialog – Example Code and Some Tips

Using the JavaScript showModalDialogfunction is a useful way for Web developers to create a modal popup. Unlike other popup functions, the showModalDialogfunction makes use of two separate HTML pages… one page as the parent page, and one page as the content of the modal dialog.

Developers will sometimes want the modal popup to be more than just a fancy version of the common alert() function. In this case, one has the option of creating a fully functional Web form in the Web page called from the showModalDialogfunction.

The Problem with using ShowModalDialog

The problem with the showModalDialogfunction is inconsistent support across the various Web browsers. Chrome still refuses to show the new form in a modal manner, instead showing it like a popup window, and Opera flat out refuses to support the command. Firefox supports the showModalDialogfunction nicely, but Internet Explorer will open a new Web page if the modal dialog form is submitted or redirected.

Fixes to Use to get showModalDialog Working Properly

Likewise, one can correct Chrome’s lack of modal support by using a traditional alert() function in the HTML body’s onBlur event. Just set the text of the alert to remind your users that they need to complete work on the modal window before working on something else. Using the alert() function is a simple and effective fix for Chrome that will not interfere with IE or FireFox where the dialog is properly modal.

The Modal Page (Child Page)

Below is the code for the child page called ModalForm.aspx. The child page has a button on it to simulate a form post event. This is done to show that by using the <base target=”_self” /> tag, the form post event will not open up a new window in Internet Explorer.

Likewise, the Chrome bug of not treating the child window as modal is corrected using the modal nature of a JavaScript alert() message that is triggered onBlur().

any chance you could post a small sample that closes the form on clicking a button. I run some JavaScript to validate, and do self.close(). and then want to run server side code to save off values. but the click event of the button does not seem to fire.The object is to save off some values to a session variable that hopefully can be saved from the calling page. Thanks

Thanks for your feedback Steve, I’ve posted a new article with a code example where the modal popup saves to the session state and then closes itself using self.close(). I hope you find it useful, cheers!