Default Text Label in Textbox using JavaScript/jQuery

html-textbox-label-text
In one of my previous article about Change Form Textbox Style on Focus, we discussed about Usability and HCI issues. Slight change in web pages/input forms can increase user experience.

Nowadays, it has became a common practice to give user labels on fields that they are editing. For example, if you see Google’s custom search textbox in any website, most of them will have a Google’s Logo in background and when user clicks on Textbox, the logo disappears. Thus we can create an input form with labels in background of textboxes. When user select the textboxes, the labels disappear enabling user to edit the textbox.

textbox-background-text-vanish

Let us see how can we use JavaScript/jQuery to achieve this.

Step 1: The HTML

We will use following simple HTML Form. Create an HTML file and Copy and paste following code.

<FORM method="post">
<TABLE>
<TR>
	<TD>Username</TD>
	<TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD>
</TR>
<TR>
	<TD>Age</TD>
	<TD><INPUT type="text" value="" name="username" title="Enter Age"/><TD>
</TR>
<TR>
	<TD>City</TD>
	<TD><INPUT type="text" value="" name="username" title="Enter City"/><TD>
</TR>
<TR>
	<TD>Comment</TD>
	<TD><INPUT type="text" value="" name="username" title="Enter Comment"/><TD>
</TR>
</TABLE>
</FORM>

Notice that while defining each text fields, we have provided title attribute. The text that is displayed on background of textbox is taken from the Title attribute. So generally the title attribute should be like “Enter Email Address” or “Type Address”.

Step 2: The CSS

Copy following CSS in your HTML file. You may want to include a separate CSS file for this.

.text-label {
	color: #cdcdcd;
	font-weight: bold;
}

The above CSS class is applied to the Textbox when user has not entered anything in it. Once the user starts typing in Textbox the CSS class is removed.

Step 3: The JavaScript

We are almost done with our implementation. Only thing left is the JavaScript code that actually add and remove css to textboxes.

$('input[type="text"]').each(function(){

	this.value = $(this).attr('title');
	$(this).addClass('text-label');

	$(this).focus(function(){
		if(this.value == $(this).attr('title')) {
			this.value = '';
			$(this).removeClass('text-label');
		}
	});

	$(this).blur(function(){
		if(this.value == '') {
			this.value = $(this).attr('title');
			$(this).addClass('text-label');
		}
	});
});

The above code is straight forward. For each textbox in the webpage, we hook handler function to events focus and blur. When Textbox is focused, check if the value is same as Title. If so, then remove the background label css and let user edit the value in textbox. And while blur event(focus lost), check the value: if user has not entered anything, set the background css again.

Online Demo


Online Demo



46 Comments

  • nick 17 October, 2009, 10:17

    hi viral..
    i use asp.net and want to try your code..
    when i run the code, a error message appears “Microsoft JScript runtime error: Object expected”

    $('input[type="text"]').each(function() {
    	this.value = $(this).attr('title');
    	$(this).addClass('text-label');
    	$(this).focus(function() {
    		if(this.value == $(this).attr('title')) {
    			this.value = '';
    			$(this).removeClass('text-label');
    		}
    	});
    
    	$(this).blur(function() {
    		if(this.value == '') {
    			this.value = $(this).attr('title');
    			$(this).addClass('text-label');
    		}
    	});
    });
    

    plz help me

    • Kemal 13 November, 2011, 5:09
              $(function () {
                  var searchBox = $('#');
                  searchBox.focus(function () {
                      if (searchBox.val() == this.title) {
                          searchBox.removeClass('text-label');
                          searchBox.val('');
                      }
                  });
                  searchBox.blur(function () {
                      if (searchBox.val() == '') {
                          searchBox.addClass('text-label');
                          searchBox.val(this.title);
                      }
                  });
                 searchBox.blur();
              });
          
  • Viral Patel 17 October, 2009, 13:42

    Hi Nick,
    The code looks fine to me. The error you are getting is because some object has not been initialized properly. Can you confirm if you have included jQuery javascript file in your code?
    You must have something like following in your html:

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
    

    You can do one thing. Take a look at source code of Online demo and see if you are missing anything in your code.

  • Mark Kadlec 19 November, 2009, 1:22

    Very nice Viral! I’m surprised that asp.net doesn’t have this type of control functionality.

  • ben 18 January, 2010, 23:55

    This is a good start, but could use some polishing. I added a check to see if the title attribute exists for field and added an onsubmit check to be sure we don’t submit default text.

    It’d also be nice to use it on textareas, which shouldn’t be too hard.

  • vikas 20 February, 2010, 2:23

    Hi, Viral
    It’s working fine with the form that load with in the same page but when I’m loading a form through Ajax in a particular div tag t his won’t work with the dynamically loaded forms.
    Is their any way to works also with dynamically loaded form?

  • James 24 February, 2010, 17:42

    Hi,

    Great! It is straightforward. I just wonder why it doesnt work if I am putting the script on an external source or even putting it on the tag. It only works when the script is positioned before the tag.

  • Md. Lutfor Rahman 6 May, 2010, 2:22

    I had need this for deperture tracing system

  • Greg 28 May, 2010, 1:19

    Any ideas on how this could be made to work with a password input?

  • Ed Cayce 10 June, 2010, 2:58

    Hey everyone, here is one I made that handles Password inputs as well, and also ignores text boxes with no Title attribute. You can’t change input types dynamically with all browsers so instead I show and hide two different inputs. You need one with ID Password and another with ID PasswordDummy, For clients with no javascript, best to set PasswordDummy to display:none initially.

    Enjoy.

    [CODE="js"]

    $(‘input’).each(function() {

    if (this.id == ‘Password’) {
    // Handle Password differently – it only gets an onblur, in which it gies invisible and activates the PasswordDummy if it is empty

    // if its blank, make it invisible and Dummy visible
    if (this.value == ”) {
    $(this).hide();
    $(“#PasswordDummy”).show();
    }
    else {
    $(this).show();
    $(“#PasswordDummy”).hide();
    }

    $(this).blur(function() {
    if (this.value == ”) {
    $(this).hide();
    $(“#PasswordDummy”).show();
    }
    else {
    $(this).show();
    $(“#PasswordDummy”).hide();
    }
    });
    }
    else if (this.id == ‘PasswordDummy’) {
    // Handle Password Dummy differently
    this.value = $(this).attr(‘title’);
    $(this).addClass(‘text-label’);

    $(this).focus(function() {
    $(this).hide();
    $(“#Password”).show();
    $(“#Password”).focus();
    });
    }
    else if ($(this).attr(‘title’) != undefined) {
    if (this.value == ”) {
    this.value = $(this).attr(‘title’);
    $(this).addClass(‘text-label’);
    }

    $(this).focus(function() {
    if (this.value == $(this).attr(‘title’)) {
    this.value = ”;
    $(this).removeClass(‘text-label’);
    }
    });

    $(this).blur(function() {
    if (this.value == ”) {
    this.value = $(this).attr(‘title’);
    $(this).addClass(‘text-label’);
    }
    });

    }

    });

    [/CODE]

  • cem 19 July, 2010, 2:40

    Hi,
    I’am a asp.net user and I want to say someting about your code.Firstly I appreciate you for your simple and chic code.I have been using it very well.But I want to add some missing code(according to me :)).My Code :

     $('input[type="text"]').each(function(){
    	   if( this.value==this.title){
    	        this.value = $(this).attr('title');
    	        $(this).addClass('text-label');
    
    	        $(this).focus(function(){
    		        if(this.value == $(this).attr('title')) {
    			        this.value = '';
    			        $(this).removeClass('text-label');
    		        }
    	        });
    
    	        $(this).blur(function(){
    		        if(this.value == '') {
    			        this.value = $(this).attr('title');
    			        $(this).addClass('text-label');
    		        }
    	        });
    	        }
            });
    

    Of Course that’s your code,not mine.But I added oneline,why?
    After the same page loading, the value of textbox continue to stand in the textBox.What will be doing is to prevent this problem. So now, after the page loading your code works very well!

  • thiviya 13 August, 2010, 10:09

    i have a problem where i call the java script in textbox using .net. pls give me a solution.

  • krishn pal 5 March, 2011, 18:21

    this field label only for input text
    like :- Enter user name (for input field)

    how can i use in password field i change “text” field in password

    it not working

    what should i do

    plz help as soon as possible

  • Shana 24 October, 2011, 22:10

    Won’t this be an issue when you need to validate required fields, though? If the user submits a form without entering anything, it will submit that default text as the value, so then it won’t properly recognize that the user didn’t fill out the required field. How do you get around this?

  • Prateek Joshi 9 December, 2011, 18:43

    it doesn’t work when we dynamically add the textbox on click of the add-more button. please provide a solution for this.

    • Viral Patel 9 December, 2011, 22:44

      Hi Prateek,
      jQuery does provide live events which can be used to map events to any current and future element, but unfortunately live() does not provide any create method which can be used to handle new element creation. So for now the simplest solution (without adding any additional plugin) would be to wrap above javascript in some function() { } and call it everytime a new element is added.

  • sweetmaanu 9 February, 2012, 20:49

    Hi
    This tutorial is really useful for me.

    I’m just building a Malayalam English online dictionary.

    this tutorial really useful for me

    Thank you very much :)

  • Nirmal 28 February, 2012, 1:48

    Thanks this was helpful.

  • Berni Ball 16 March, 2012, 1:18

    Could anyone tell me how to add a onsubmit check to make sure default values aren’t submitted?

    Many thanks

  • Berni Ball 19 March, 2012, 23:39

    If anyone needs to add a check on onsubmit:
    http://stackoverflow.com/questions/9727032/text-labels-in-textbox-being-passed-onsubmit

  • niraj 29 March, 2012, 17:30

    hi, all

    can anyone tell me, how I can disply ” division of two combobox values and then multiplying the answer with the a contant number” in a texbox in nuace PDF professional 5.

  • daham 2 May, 2012, 0:21

    This was really helpful. Thanks

  • Morten 13 July, 2012, 20:10

    very helpfull

  • Sayed Ahmad 31 August, 2012, 19:09

    Thanks a lot I place the whole Jquery code inside the
    $(document).ready(function(){ your code here });
    it work properly

  • Girish 7 September, 2012, 14:46

    hi viral nice tutorial. how can i use this for tag html:text ?

  • Mayur 16 February, 2013, 8:59

    So you cannot put the javascript in the header section or else it won’t work. Javascript has to be below the form for this to work. It wasn’t working for me at first then i checked the source of online demo and saw that javascript was at the end after Is there any way to make this work by having javascript in the header?

  • Marcelo 26 February, 2013, 3:06

    Straight and easy. Thank you!

  • Agung Setiawan 27 February, 2013, 13:32

    so you want to add watermark in your tex tbox?
    now it is so much easy to do it, just use placeholder attribute inside input tag
    ex:

    • sindhu 18 March, 2014, 14:47

      hai friend do u have code for watermarking text box using ajax in jsp ma…pls reply dawhich is i will entermy emp id if pan is there….in database i want the pan and dob text box to be enabled..which is disabled state….otherwise…dob and doj have to be enabled

  • Agung Setiawan 27 February, 2013, 13:33

    so you want to add watermark in your tex tbox?
    now it is so much easy to do it, just use placeholder attribute inside input tag
    ex:

    <input type="text" placeholder="Enter Username" id="username" />
    
    • Sarah 3 April, 2013, 0:34

      Man, thank you sooooo much! I was trying to use javascript/jquery but I don’t know a lot. you saved me!!

    • Zachary 15 August, 2013, 1:26

      Agung, thanks. Thats a lot easier and basically does the same thing!

  • dave 4 March, 2013, 18:22

    Great solution, thanks

  • kedar 29 March, 2013, 14:17

    Really You made my day.. ..Many Thanks

  • Samar 14 May, 2013, 1:45

    This post is very nice Post. It is working for me as well.
    Thanks you so much Viral

  • Koveksi Kaos Bandung 14 May, 2013, 22:36

    it’s very nice tutorial jquery labeling text box… i’m interesting to use it for my website. thanks

  • mahesh 28 June, 2013, 13:16

    how do i integrate it in one html file

  • sathik 26 August, 2013, 13:21

    this one is great solution for my doubt

  • anji 17 September, 2013, 10:11

    this one is good actuallly i want jquery validation in java

  • anji 17 September, 2013, 10:11

    Please tel me suggestion

  • Pardeep 29 September, 2013, 11:54

    Hi Viral ,
    .Focus and .blur not working on IPAD,
    is there any other way to do this.

  • saneera 4 October, 2013, 7:33

    it’s very nice tutorial jquery labeling text box… i used this in my web site

  • pankaj 9 May, 2014, 10:41

    Nice article. I use placeholder attribute as mentioned by Agung Setiawan. The difference is that it disappears when you start typing and not on click. It also saves a lot of code.

     <input type="text" placeholder="Enter Username" id="username" /> 
  • izo 23 June, 2014, 15:06

    wonderful

  • konveksi kaos bandung - kaoskaosbandung 25 September, 2014, 14:14

    it’s nice tutorial, i’ll try this for my website

  • Pratik 6 October, 2014, 13:29

    Hey Viral,
    i can’t see the output i.e.
    label on textbox…
    plz help me…

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]

Current ye@r *