Watermark textbox with JQuery

The more I explore JQuery, the more I get impressed with its power and flexibility. With classic JavaScript what you are writing with ten lines of code. The same functionality you can achieve with JQuery in fewer lines. This is the one good reason I prefer to user JQuery in my projects. Today I will explain you how to create watermark textbox with JQuery.

It’s really simple to create a watermark textbox, and you not need to write down number of line of codes. So let’s get started.

Create a simple HTML page either in visual studio or notepad. I prefer to use visual studio. On your HTML page add script tag and give path to your JQuery script file.

Add two labels and textboxes on your page, as shown below.

Watermark textbox will show a default message until unless user not provides an input. This looks good as it provides information to the user that in the textbox what he is going to write. It makes your website more users friendly. We will add JavaScript tag inside our head section. And call the ‘document.read’ function. Inside the function we will check the focus on input textbox. In the example we are using only two textboxes so I am using ‘Select by Element’ technique. But if you want to apply watermark on any specific textbox you can call if by its Id, or you can create a class and apply that class on the textboxes you want to mark as watermark. We added a default value in our example like ‘Enter first name’, so when page loads or user not type anything a default value will appear.

We add a focus event on the input boxes and check the textbox value. In JQuery Val is used to get and set the values. So this is it, our watermark textbox is ready. And as you can see we add the focus by calling ‘DOM Element’ so this focus function applies to both textboxes. But there is one problem when the focus is out and user didn’t type anything in the textbox we should display back the default value. So on focus out we will write down a function and check if nothing is typed in the textboxes placed the default value back.

.blur is the function in JQuery used for focus out. We will trim the value so if any space is entered we will remove that and check the value in the textbox. If it’s empty, set the textbox default value again. The complete source code of this post is written below.



Tagged with: , , ,