blog about graphic design, web design and marketing

The D. Drew Design Blog
9
feb 10

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.