How to Set and remove the default value of a text box using javascript and jquery? Code _ javascript skills

Source: Internet
Author: User
This article describes how to set and remove the default value of a text box using javascript and jquery. This article implements an effect similar to html5placeholder (blank prompt, for more information, see set and remove the default value of the text box. For example, when you place the cursor in the text box, the gray text disappears.

1. You can simply add the onfocus attribute to the input text box, as shown in the following code:

The Code is as follows:


Onfocus = 'if (this. value = "enter a keyword to search") {this. value = "";};'
Onblur = 'if (this. value = "") {this. value = "enter a keyword to search" ;}; '>

In fact, the onfocus attribute is quite useful. You can also change the css style through the onfocus attribute, as shown in the following code:

The Code is as follows:


Onfocus = 'if (this. value = "enter a keyword to search") {this. value = "" ;}; this. className = "input01 "'
Onblur = 'if (this. value = "") {this. value = "enter a keyword to search" ;}; this. className = "input02" '>

2. jquery can also be used for implementation:

The Code is as follows:


$ (Document). ready (function (){
Var vdefault = $ ('# keyword'). val ();

$ ('# Keyword'). focus (function (){
// When the focus is obtained, if the value is the default value, it is set to null.
If ($ (this). val () = vdefault ){
$ (This). val ("");
}
});
$ ('# Keyword'). blur (function (){
// If the value is null when the focus is lost, it is set to the default value.
If ($ (this). val () = ""){
$ (This). val (vdefault );;
}
});
});

Of course there are many ways to implement it. Here I just used it...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.