Using hints inside text fields instead of labels


The following code example demonstrates replacing labels with hints that appear as temporary values within text fields; akin to placeholder attribute in HTML5.

A custom attribute called data-hint-value contains the hint value to which a text field gets initialized. That value represents what typically would be the value of a label associated with the text field. It is cleared when the text field receives focus, and filled with hint value if text field is empty on blur.

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <link rel="shortcut icon" href="favicon.ico">
    <script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
</head>
<body>
    <input id="name" type="text" data-hint-value="your name" />
    <script type="text/javascript">

        function setAllTextToHint() {
            $(":text").each(function (index) {
                hint = $(this).attr("data-hint-value");
                if (hint) $(this).val(hint);
            });
        }

        function isTextValueValid(id) {
            var ret = false;
            $(":text").each(function (index) {
                thisId = $(this).attr("id");
                if (thisId == id) {
                    hint = $(this).attr("data-hint-value");
                    value = $(this).val();
                    if (value == hint || value == "") {
                        alert("Please specify " + hint);
                        $(this).val(hint);
                        $(this).focus();
                        return;
                    } else {
                        ret = true;
                        return;
                    }
                }
            });
            return ret;
        }

        $(":text").focus(function () {
            hint = $(this).attr("data-hint-value");
            if ($(this).val() == hint)
                $(this).val("");
        });

        $(":text").blur(function () {
            hint = $(this).attr("data-hint-value");
            if ($(this).val() == "") {
                $(this).val(hint);
            }
        });
    </script>

setAllTextToHint is a helper function that sets all text fields to their hint values. isTextValueValid may be used to check whether a text field contains some value, and alerts the user when it does not. Tweak these as you see fit.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s