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

后端 未结 13 580
悲哀的现实
悲哀的现实 2021-01-29 22:54

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

相关标签:
13条回答
  • 2021-01-29 23:33
    <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.

    0 讨论(0)
  • 2021-01-29 23:35

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

    <input type="text" name="user" placeholder="Username">
    
    0 讨论(0)
  • 2021-01-29 23:36
    <input name="searchbox" onfocus="if (this.value=='search') this.value = ''" type="text" value="search">
    

    A better example would be the SO search button! That's where I got this code from. Viewing page source is a valuable tool.

    0 讨论(0)
  • 2021-01-29 23:38

    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

    0 讨论(0)
  • 2021-01-29 23:43

    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

    0 讨论(0)
  • 2021-01-29 23:47

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

            <%= f.text_field :user_email,:value=>"",:placeholder => "Eg:abc@gmail.com"%>
    

    Simplest way...

    0 讨论(0)
提交回复
热议问题