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

后端 未结 5 1623
名媛妹妹
名媛妹妹 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.

提交回复
热议问题