How do I get form values to disappear when I enter

2019-03-19 14:42发布

问题:

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 people know to enter there name there.

My question though is how do you get the initial value to vanish when they enter that field so that the initial value is only a hint and not a permanent value that they have to erase before they can type in their name?

Thanks!

回答1:

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='';"/>


回答2:

A much easier way could possibly be:

placeholder="Name"


回答3:

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.



回答4:

Basic javascript:

<input type="text" value="name" onfocus='if(this.value=="name"){this.value="";}' />


回答5:

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.