How do I get form values to disappear when I enter the field?

后端 未结 5 1606
名媛妹妹
名媛妹妹 2021-02-08 21:39

I am making a simple form with about eight input fields. I want the initial value in the field to indicate what people are supposed to enter. For example value=\"name\" so that

相关标签:
5条回答
  • 2021-02-08 22:05

    Just for S&G's I thought I would post a reusable jQuery solution for this problem.

    var formDefaulter=function(){
        //Class to hold each form element
        var FormElement=function(element){
            var that=this;
            this.element=element;
    
            var initialVal=this.element.val();
            var isEdited=false;
    
            this.element.focus(function(){clearBox()});
            this.element.blur(function(){fillBox()});
    
            var clearBox=function(){
                if(!isEdited){
                    that.element.val("");
                    isEdited=true;
                }
            }
            var fillBox=function(){
                if(that.element.val()==""){
                    that.element.val(initialVal);
                    isEdited=false;
                }
            }
        }
    
        var add=function(elementId){
            new FormElement($('#'+elementId));
        }
    
        return{
            add:add
        }
    }();
    

    Then you just have to attach each element using an ID attribute value. Like so:

    $(function(){
        formDefaulter.add('contact_name');
        formDefaulter.add('contact_email');
        formDefaulter.add('contact_msg');
    });
    

    This also refills the form element with its original value if its content is deleted. Anyway, hopefully this is helpful to someone.

    0 讨论(0)
  • 2021-02-08 22:10

    This is how you should do it.

    <input type="text" value="name" onfocus="this.value = this.value=='name'?'':this.value;" onblur="this.value = this.value==''?'name':this.value;">
    

    If they click on it and click off the default value will go back. If they click on it and type something in, it won't try to erase what they put if they go back to click on it again.

    0 讨论(0)
  • 2021-02-08 22:13

    A much easier way could possibly be:

    placeholder="Name"
    
    0 讨论(0)
  • 2021-02-08 22:30

    Set the 'default' value to "Name". Then, using javascript and the 'onfocus' event, clear the field.

    So you would have:

    <input type="textbox" value="Name" onfocus="if (this.value=='Name') this.value='';"/>
    
    0 讨论(0)
  • 2021-02-08 22:30

    Basic javascript:

    <input type="text" value="name" onfocus='if(this.value=="name"){this.value="";}' />
    
    0 讨论(0)
提交回复
热议问题