[javascript] Delete default value of an input text on click

I have an input text :

<input name="Email" type="text" id="Email" value="[email protected]" />

I want to put a default value like "What's your programming question ? be specific." in StackOverFlow, and when the user click on it the default value disapear.

This question is related to javascript html input default-value

The answer is


<input name="Email" type="text" id="Email" placeholder="enter your question" />

The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format).

The short hint is displayed in the input field before the user enters a value.

Note: The placeholder attribute works with the following input types: text, search, url, tel, email, and password.

I think this will help.


This is somewhat cleaner, i think. Note the usage of the "defaultValue" property of the input:

<script>
function onBlur(el) {
    if (el.value == '') {
        el.value = el.defaultValue;
    }
}
function onFocus(el) {
    if (el.value == el.defaultValue) {
        el.value = '';
    }
}
</script>
<form>
<input type="text" value="[some default value]" onblur="onBlur(this)" onfocus="onFocus(this)" />
</form>

EDIT: Although, this solution works, I would recommend you try MvanGeest's solution below which uses the placeholder-attribute and a javascript fallback for browsers which don't support it yet.

If you are looking for a Mootools equivalent to the JQuery fallback in MvanGeest's reply, here is one.

--

You should probably use onfocus and onblur events in order to support keyboard users who tab through forms.

Here's an example:

<input type="text" value="[email protected]" name="Email" id="Email"
 onblur="if (this.value == '') {this.value = '[email protected]';}"
 onfocus="if (this.value == '[email protected]') {this.value = '';}" />

Here is a jQuery solution. I always let the default value reappear when a user clears the input field.

<input name="Email" value="What's your programming question ? be specific." type="text" id="Email" value="[email protected]" />

<script>
$("#Email").blur(
    function (){
        if ($(this).val() == "")
            $(this).val($(this).prop("defaultValue"));
        }
).focus(
    function (){
        if ($(this).val() == $(this).prop("defaultValue"))
            $(this).val("");
    }
);
</script>

Here is very simple javascript. It works fine for me :

// JavaScript:

function sFocus (field) {
    if(field.value == 'Enter your search') {
        field.value = '';
    }
    field.className = "darkinput";
}

function sBlur (field) {
    if (field.value == '') {
        field.value = 'Enter your search';
        field.className = "lightinput";
    }
    else {
        field.className = "darkinput";
    }
}
// HTML
<form>
  <label class="screen-reader-text" for="s">Search for</label>
  <input
    type="text"
    class="lightinput"
    onfocus="sFocus(this)" 
    onblur="sBlur(this)"
    value="Enter your search" name="s" id="s"
  />
</form>

Why remove value? its useful, but why not try CSS

input[submit] {
   font-size: 0 !important;
}

Value is important to check & validate ur PHP


we can do it without using js in the following way using the "placeholder" attribute of html5 ( the default text disappears when the user starts to type in ,but not on just clicking )

<input type="email" id="email" placeholder="[email protected]">

see this: http://www.w3schools.com/html/tryit.asp?filename=tryhtml5_input_placeholder


Using jQuery, you can do:

$("input:text").each(function ()
{
    // store default value
    var v = this.value;

    $(this).blur(function ()
    {
        // if input is empty, reset value to default 
        if (this.value.length == 0) this.value = v;
    }).focus(function ()
    {
        // when input is focused, clear its contents
        this.value = "";
    }); 
});

And you could stuff all this into a custom plug-in, like so:

jQuery.fn.hideObtrusiveText = function ()
{
    return this.each(function ()
    {
        var v = this.value;

        $(this).blur(function ()
        {
            if (this.value.length == 0) this.value = v;
        }).focus(function ()
        {
            this.value = "";
        }); 
    });
};

Here's how you would use the plug-in:

$("input:text").hideObtrusiveText();

Advantages to using this code is:

  • Its unobtrusive and doesn't pollute the DOM
  • Code re-use: it works on multiple fields
  • It figures out the default value of inputs by itself



Non-jQuery approach:

function hideObtrusiveText(id)
{
    var e = document.getElementById(id);

    var v = e.value;

    e.onfocus = function ()
    {
        e.value = "";
    };

    e.onblur = function ()
    {
        if (e.value.length == 0) e.value = v;
    };
}

Just use a placeholder tag in your input instead of value


Enter the following inside the tag, just add onFocus="value=''" so that your final code looks like this:

<input type="email" id="Email" onFocus="value=''"> 

This makes use of the javascript onFocus() event holder.


I didn't see any really simple answers like this one, so maybe it will help someone out.

var inputText = document.getElementById("inputText");
inputText.onfocus = function(){ if (inputText.value != ""){ inputText.value = "";}; }
inputText.onblur = function(){ if (inputText.value != "default value"){ inputText.value = "default value";}; }

Here is an easy way.

#animal represents any buttons from the DOM.
#animal-value is the input id that being targeted.

$("#animal").on('click', function(){
    var userVal = $("#animal-value").val(); // storing that value
    console.log(userVal); // logging the stored value to the console
    $("#animal-value").val('') // reseting it to empty
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

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 input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to default-value

How to set a default value in react-select How to set default values in Go structs What is the default value for Guid? CURRENT_DATE/CURDATE() not working as default DATE value Entity Framework 6 Code first Default value Default values and initialization in Java Python argparse: default value or specified value Javascript Get Element by Id and set the value Why is the default value of the string type null instead of an empty string? SQL Column definition : default value and not null redundant?