
Snazzy jQuery Form Alert Boxes
For a recent client, I wanted to write a script that would alert a user to not leave a field blank. Using jQuery, I wrote a script that animates a small alert box into a position relative to the input box in question. If the user "focuses" on the particular input box, then "blurs" (clicks off of it, or clicks elsewhere) without inputting anything, the alert box will insert itself into the DOM directly above the particular <input> in question alert them that they left it empty.
Should they go back to fill it in, when they click on it, the alert box will animate away (and remove itself from the DOM) while they type in their information.
The code is here:
$(document).ready(function(){
// You can set your input selector with the following
$("input, textarea").focus(function() {
if($(this).prev().attr("class") == "formalert") {
$(this).prev().animate({
opacity: '0',
// adjust this line for your positioning attribute here and subtract 10px from its vertical alignment.
margin: '0px 0 0 320px'
}, 100, "swing", function() {
$(this).remove();
});
}
});
$("input, textarea").blur(function() {
if($(this).attr("value") == "") {
$(this).before('<div class="formalert">This field may not be left blank.</div>');
$('div.formalert').animate({
opacity: '1',
// adjust this line for your positioning attribute here and add 10px to its vertical alignment.
margin: '10px 0 0 320px'
}, 100, "swing"
);
}
});
});
This is the original CSS from the element in question:
.formalert {
background: #900;
color: #fff;
font-size: 10px;
width: auto;
padding: 5px;
border: #600 solid 1px;
position: absolute;
margin-left: 300px;
opacity: 0;
}
Remember, this is only a Javascript alert, and it doesn't properly substitute for server-side input verification. This is only a user interface touch-up for user convenience purposes.
Click here to see this code in action.
Contact me if you have any questions.
Tags: jquery, javascript, user interface, code, html, tutorial
Some other articles you might enjoy...
| jQuery Vertical Align Function | Wednesday, October 27, 2010 |
| JQuery/PHP: Simple Random Text Generation Box | Monday, June 22, 2009 |
| jQuery is-or-is-child-of function | Saturday, June 25, 2011 |
| Fixing the 100% width text input field | Friday, July 1, 2011 |
| Creating An Image Management System for Your Website with Smart Image Resizer and Lightbox 2 | Saturday, July 11, 2009 |
design 16 articles
user interface 7 articles
php 7 articles
code 7 articles
web 6 articles
jquery 6 articles
tutorial 6 articles
picture 5 articles
marketing 5 articles
html 4 articles
2012
2011
2010
2009