Web Development Blog

by Ei Sabai Nyo

17 Jun, 2010

Clear default text in input boxes on click with jQuery    

The following Javascript will clear default text value in input boxes when you click on them. To trigger the Javascript, you’ll need to specify both title and value attributes and set class of the input field to “text”. jQuery library is required for this to work.

Javascript

$('.text').focus(function () {
	if ($(this).val() == $(this).attr("title")) {
		$(this).val("");
	}
}).blur(function () {
	if ($(this).val() == "") {
		$(this).val($(this).attr("title"));
	}
});

Examples:

<input type="text" name="q" class="q text" value="Search for terms" title="Search for terms" />

<input type="password" name="password" class="text" value="Password" title="Password"  />
Love what you've just read? Subscribe to our newsletter to receive tips, resources and special offers related to web development & design.
Your name:   Your email:  

5 Responses to “Clear default text in input boxes on click with jQuery”

  1. James says:

    Is this not 100x more simpler? :)

  2. eisabai says:

    Hi James,

    Your example does look simpler but it’s not an ideal solution because Javascript is not accessed via DOM and it will require you to put the same piece of code multiple times if you want to apply it to more than one input box.

  3. chayan says:

    Alternate Method :-
    ==============

    $(document).ready(function(){

    $(“#btnclear”).click(function()
    { $(‘:text’).val(“”); });
    });

    ====
    #btnclear is the id of the button

  4. chayan says:

    $(document).ready(function(){
    $(“#btnclear”).click(function()
    { $(‘:text,textarea’).val(“”); });
    });

    this will clear text area too

Profile PicHello! Welcome to Web development blog! My name is Ei Sabai and on this blog, I write about web development, mobile app development, latest web technologies and the likes. Read more about me or have a look at some of the tips & resources I've written.
Subscribe to our newsletter to receive tips, resources and special offers related to web development & design.
We do NOT spam.
Your name:  
Your email:  

Tips & Resources

Tips & Resources
WordPress Web Hosting
Recommended web hosting providers for WordPress 3.0
iPhone Native App Development
Important steps into iPhone app development for beginners
iPhone Web App Development
Tips for iPhone web app development
Coupons for Web Developers
Get discounts on web hosting, domain names, templates, etc
10 Useful jQuery Snippets
Easy-to-use jQuery snippets for any website
HTML Email Newsletter
Step-by-step tutorial on how to code an HTML email newsletter
  • bluehost Hosting $6.95/month
  • Joomla Templates

Recommended Book

Categories