A couple of weeks ago I wrote about Cory S.N. LaViska’s new jQuery Alert Dialogs Plugin. Since then I have used it quite a bit and have been really happy with its ease of use and simplicity. At the end of the my first post about the plugin I said I would try and show you a way to setup an alert from the server side so that it shows up once the web page loads.
So when might you do this? You might want an alert on page load to let the user know that a task such as a delete was successful or probably more importantly and less intrusive would be to only let the user know something went wrong.
The method I came up with to popup the dialog on page load involves a single hidden field. All you have to do is pass the type of alert, message and title you want through the hidden field and the jQuery/JavaScript will take this data on page load and create the desired alert. Remember, you will need my version of the plugin (in the download) to be able to choose the different type of dialogs (info, success, warning, error). Also, the css and images for the dialogs originally came from Janko’s great post CSS Message Boxes for different message types.
Live Demo | Download (HTML, CSS, JS)
Screenshot of End Product:
jQuery:
<script type="text/javascript">
$(document).ready(function() {
//See if an alert has been setup from the server side
CheckAlert();
//Add a click event to each delete icon
$("#tableTasks tbody td:last-child").each(function() {
$(this).click(function() {
var txt = $("td:first-child", $(this).parent("tr")).html()
jAlert("confirm", "Are you sure you want to delete the task '" + txt + "'", "Confirm", function(r) {
if (r == true) {
//You would most likely want to set the HiddenFieldAlert value on the server once the task has been deleted
//I am doing it here so that this demo can remain plain html, css, js
$("#HiddenFieldAlert").val("success;The task '" + txt + "' would of been deleted.;Success");
CheckAlert();
}
});
}).css("cursor", "pointer");
});
});
function CheckAlert() {
var alertData = $("#HiddenFieldAlert");
if (alertData.val()) {
var alertDataArray = alertData.val().split(";")
jAlert(alertDataArray[0], alertDataArray[1], alertDataArray[2], null);
alertData.val('');
}
}
</script>
Please be sure to checkout the live demo and download. Let me know in the comments what you think.