Found myself wanting to provide a modal dialog (preferably in jQuery of course!) to gate first-time page visitors. The requirements were:
- On page load, display modal dialog with a form to request basic contact information
- Disable the “esc” key to force the user to enter the info or click a “no thanks” button
- Hide the x which appears in the dialog
My approach was using the jQuery dialog, $.post to send the contact information to my controller and then hide the modal dialog. We can do this in three easy steps:
Configure jQuery dialog
The jQuery dialog has some nifty properties out of the box to handle things like, disabling the esc key, displaying the modal dialog on page load, along with the usual suspects: style, size, resizing. Here is what my call looks like, with our special properties highlighted in blue:
$(function() {
$("#registrationform").dialog({
height: 470,
width: 520,
resizable: false,
<span style="color: #0000ff;">autoOpen</span>: true,
<span style="color: #0000ff;">modal</span>: true,
<span style="color: #0000ff;">closeOnEscape</span>: false
});
});
1
<h2>Hide the dialog's x button</h2>
The dialog shows a x in the top right corner by default, and there are no properties to hide it. The best way I found is using some old fashioned CSS:
1
<style>
.ui-dialog .ui-dialog-titlebar-close { display: none; }
</style>
So that is all it takes to set the dialog to display on page load and prevent users from escaping out or closing the form. Next is sending the results back to the server, which is pretty simple using $.post.
Post back to the server and process results
First, you need to handle a button’s click event, and have some logic to process the result. I primarily develop in ASP.NET MVC, but you could very easily use this technique in PHP, Ruby, etc. Here is the function:
function Register() {
$.post("/Contact/RegisterGuest",
{
FirstName: $("#FirstName").val(),
LastName: $("#LastName").val(),
Email: $("#Email").val(),
Phone: $("#Phone").val()
},
function(data) {
Result = eval('(' + data + ')');
if (Result == "") {
$('#registrationform').dialog('close');
$("#registrationform").hide("fast");
$("#result").show("fast");
}
else {
$("#errorblock").html("<ul>" + Result + "</u>");
}
});
}
Breaking down the function, we’re posting to the RegisterGuest method for the Contact controller, with the FirstName, LastName, Email, and Phone fields, and processing the result. Typically I’ll return any errors in listitem tags, so an empty Result means no errors occurred on the server-side. If the Result variable is empty, we hide the dialog and show whatever was hidden. Otherwise we set the html value for a pre-defined div to be the error list.
