Quantcast
Viewing all articles
Browse latest Browse all 21

Doing away with labels for text fields

The following code example does away with labels for text fields. A custom attribute called data-default-value contains the default 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 default 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-default-value="your name" />
    <script type="text/javascript">

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

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

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

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

Filed under: JavaScript Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 21

Trending Articles