Saturday, August 15, 2009

Red Alert!

Here's a tidbit we used in the jQuery and ColdFusion class. You can write your own functions to replace JavaScript functions. The example for this involved writing an alert() function that displays error messages in a nice jQuery-created popup div instead of the ugly old JavaScript alert box. When applied, alerts (including those thrown by ColdFusion-generated validation JavaScript) look like this:


Of course, you can style the message any way you like--it's just in the CSS. As with all class examples, this is intended as a launching point for your exploration, rather than a finished tool ready for production. Here's the code; we'll go through line by line tomorrow.

<html>
<head>
<title>Javascript Alert Test</title>
<script type="text/javascript" src="../jquery/jquery.js"></script>
<style type="text/css">
#msgDiv {
height: auto;
width: 200px;
font-family: Tahoma, Helvetica, sans-serif;
font-size: 80%;
text-align: center;
background-color: #FFAAAA;
border: 1px solid red;
position: absolute;
top: 60px;
left: 50%;
margin-left: -100px;
}
#msgHeader {
background-color: red;
color: white;
font-weight: bold;
}
#msgText {
padding: 5px;
}
</style>
</head>
<body onLoad="alert('Hah!');">
<h2>CFFORM with Custom Alert</h2>
<cfform name="myForm" action="" method="post">
Full Name: <cfinput type="text" name="fullName" id="fullName" required="Yes" message="Enter your full name." /><br />
Email: <cfinput type="text" name="email" id="email" validate="email" required="yes" message="Enter your valid email address." /><br />
<cfinput type="submit" name="btnRegister" value="register" />
</cfform>
<script type="text/javascript">
function alert(msg){
if(title == undefined){
title = 'foo';
}
msgText = '';
if (msg.typeOf = "Array"){
for (i=0; i<msg.length;i++){
if (msg[i] == String.fromCharCode(10)){
msgText += '<br />';
} else {
msgText += msg[i];
}
}
} else {
msgText = msg;
}
alertHTML = '<div id="msgDiv"><div id="msgHeader">Error:</div><div id="msgText"</div></div>';
$("body").append(alertHTML);
$("#msgDiv").hide().fadeIn();
$('#msgText').html(msgText + '<br /><input type="button" value="OK">')
$('#msgDiv').click(function(){
$(this).remove();
});
}
</script>
</body>
</html>

No comments: