[html] How to create a label inside an <input> element?

I would like to insert a descriptive text inside an input element that disappers when the user click on it.

I know it is a very common trick, but I do not know how to do that..

What is the simplest/better solution?

This question is related to html forms label placeholder

The answer is


You do not need a Javascript code for that...
I think you mean the placeholder attribute. Here is the code:

<input type="text" placeholder="Your descriptive text goes here...">



The default text will be grey-ish and when clicked, it will dissapear!


Please use PlaceHolder.JS its works in all browsers and very easy for non html5 compliant browsers http://jamesallardice.github.io/Placeholders.js/


The common approach is to use the default value as a label, and then remove it when the field gains the focus.

I really dislike this approach as it has accessibility and usability implications.

Instead, I would start by using a standard element next to the field.

Then, if JavaScript is active, set a class on an ancestor element which causes some new styles to apply that:

  • Relatively position a div that contains the input and label
  • Absolutely position the label
  • Absolutely position the input on top of the label
  • Remove the borders of the input and set its background-color to transparent

Then, and also whenever the input loses the focus, I test to see if the input has a value. If it does, ensure that an ancestor element has a class (e.g. "hide-label"), otherwise ensure that it does not have that class.

Whenever the input gains the focus, set that class.

The stylesheet would use that classname in a selector to hide the label (using text-indent: -9999px; usually).

This approach provides a decent experience for all users, including those with JS disabled and those using screen readers.


<input name="searchbox" onfocus="if (this.value=='search') this.value = ''" onblur="if (this.value=='') this.value = 'search'" type="text" value="search">

Add an onblur event too.


In my opinion, the best solution involves neither images nor using the input's default value. Rather, it looks something like David Dorward's solution.

It's easy to implement and degrades nicely for screen readers and users with no javascript.

Take a look at the two examples here: http://attardi.org/labels/

I usually use the second method (labels2) on my forms.


When you start typing it will disappear.If empty it will appear again.

        <%= f.text_field :user_email,:value=>"",:placeholder => "Eg:[email protected]"%>

Simplest way...


Here is a simple example, all it does is overlay an image (with whatever wording you want). I saw this technique somewhere. I am using the prototype library so you would need to modify if using something else. With the image loading after window.load it fails gracefully if javascript is disabled.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1;" />
    <meta http-equiv="Expires" content="Fri, Jan 1 1981 08:00:00 GMT" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Cache-Control" content="no-cache" />
    <style type="text/css" >

        input.searcher
        {
            background-image: url(/images/search_back.png);
            background-repeat: no-repeat;
            background-attachment: scroll;
            background-x-position: left;
            background-y-position: center;
        }

    </style>

    <script type="text/javascript" src="/logist/include/scripts/js/prototype.js" ></script>
</head>
<body>
    <input type="text" id="q" name="q" value="" />

    <script type="text/javascript" language="JavaScript" >
    //  <![CDATA[
        function f(e){
            $('q').removeClassName('searcher');
        }

        function b(e){
            if ( $F('q') == '' )
            {
                $('q').addClassName('searcher');
            }
        }

        Event.observe( 'q', 'focus', f);
        Event.observe( 'q', 'blur', b);
        Event.observe( window, 'load', b);

    //  ]]>
    </script>
</body>
</html>

One hint about HTML property placeholder and the tag textarea, please make sure there is no any space between <textarea> and </textarea>, otherwise the placeholder doesn't work, for example:

<textarea id="inputJSON" spellcheck="false" placeholder="JSON response string" style="flex: 1;"> </textarea>

This won't work, because there is a space between...


If you're using HTML5, you can use the placeholder attribute.

<input type="text" name="user" placeholder="Username">

I think its good to keep the Label and not to use placeholder as mentioned above. Its good for UX as explain here: https://www.smashingmagazine.com/2018/03/ux-contact-forms-essentials-conversions/

Here example with Label inside Input fields: codepen.io/jdax/pen/mEBJNa


use this

style:

<style type="text/css">
    .defaultLabel_on { color:#0F0; }
    .defaultLabel_off { color:#CCC; }
</style>

html:

javascript:

function defaultLabelClean() {
    inputs = document.getElementsByTagName("input");
    for (var i = 0; i < inputs.length; i++)  {
        if (inputs[i].value == inputs[i].getAttribute("innerLabel")) {
            inputs[i].value = '';
        }
    }
}

function defaultLabelAttachEvents(element, label) {
    element.setAttribute("innerLabel", label);
    element.onfocus = function(e) {
        if (this.value==label) {
            this.className = 'defaultLabel_on';
            this.value = '';
        }
    }
    element.onblur = function(e) {
        if (this.value=='') {
            this.className = 'defaultLabel_off';
            this.value = element.getAttribute("innerLabel");
        }
    }

    if (element.value=='') {
        element.className = 'defaultLabel_off';
        element.value = element.getAttribute("innerLabel");
    }
}


defaultLabelAttachEvents(document.getElementById('MYID'), "MYLABEL");

Just remember to call defaultLabelClean() function before submit form.

good work


I've put together solutions proposed by @Cory Walker with the extensions from @Rafael and the one form @Tex witch was a bit complicated for me and came up with a solution that is hopefully

error-proof with javascript and CSS disabled.

It manipulates with the background-color of the form field to show/hide the label.

<head>

<style type="text/css">
<!--
    input {position:relative;background:transparent;} 
-->
</style>

<script>
    function labelPosition() {
        document.getElementById("name").style.position="absolute"; 
            // label is moved behind the textfield using the script, 
            // so it doesnt apply when javascript disabled
    }
</script>

</head>
<body onload="labelPosition()">

<form>
        <label id="name">Your name</label>
        <input type="text" onblur="if(this.value==''){this.style.background='transparent';}" onfocus="this.style.background='white'">
</form>

</body>

View the script in action: http://mattr.co.uk/work/form_label.html


Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to forms

How do I hide the PHP explode delimiter from submitted form results? React - clearing an input value after form submit How to prevent page from reloading after form submit - JQuery Input type number "only numeric value" validation Redirecting to a page after submitting form in HTML Clearing input in vuejs form Cleanest way to reset forms Reactjs - Form input validation No value accessor for form control TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

Examples related to label

How to set label size in Bootstrap How do I change the text size in a label widget, python tkinter Change grid interval and specify tick labels in Matplotlib Editing legend (text) labels in ggplot How to change Label Value using javascript React ignores 'for' attribute of the label element How to dynamically update labels captions in VBA form? why I can't get value of label with jquery and javascript? What does "for" attribute do in HTML <label> tag? Get Application Name/ Label via ADB Shell or Terminal

Examples related to placeholder

Keep placeholder text in UITextField on input in IOS HTML Input - already filled in text Add placeholder text inside UITextView in Swift? Bootstrap select dropdown list placeholder fail to change placeholder color with Bootstrap 3 Not showing placeholder for input type="date" field Use Font Awesome Icon in Placeholder How do I put hint in a asp:textbox How to support placeholder attribute in IE8 and 9 HTML5 image icon to input placeholder