Page 1 of 1

jQuery default input value plugin Rate Topic: -----

#1 Jstall  Icon User is offline

  • Lurker
  • member icon

Reputation: 434
  • View blog
  • Posts: 1,042
  • Joined: 08-March 09

Posted 22 September 2011 - 04:26 PM

Basic jQuery Default Input Value Plugin

Hello there. This is my first shot at creating a tutorial, so please bear with me :).

As the title states this tutorial will focus on building a (useful, in my opinion) jQuery plugin that will provide default value for input and textarea elements. When the element gets focus the default text will disappear so the user can enter a value. If the element loses focus and nothing was entered then the default value will pop back into the element. This plugin will also add and remove classes to the element depending on it's state, this can be useful for formatting.

This type of plugin can be a great space saver in forms in lieu of using labels. Also the default text can be much more verbose than a simple label and thus create a more intuitive experience for the user.

Please note: This tutorial assumes that you have fairly good working knowledge of jQuery but are new to creating plugins.

Alright, lets begin then shall we?

Create a new Javascript file and name it jQuery.defaultInput.js . This follows the standard naming convention for jQuery plugins which takes the form jQuery.pluginName.js.

When creating a plugin,the first thing one should do is create a closure like so:
(function($){
 //plugin code goes here. 
})(jQuery);



What this is doing is creating an anonymous function and calling it all at once. The function has one parameter, the $. One argument is passed to this function, jQuery. This allows us to explicitly map the $ sign to jQuery. This is done because other Javascript libraries use the $ to alias their libraries and since we want our plugin to be easily implemented into existing projects this ensures compatibility.

If you are still a little fuzzy on this concept copy and paste this into a file you can view in a browser:
<script type = "text/javascript">
(function(message){
 alert(message);
})("Hello World");
</script>



This is doing the same thing that our jQuery closure is doing except this time the functions parameter is message and we are passing the string "Hello World" as the argument.

Back to our plugin!

There is more code that should exist in pretty much every plugin implementation. Add lines to your code so that in it's entirety it looks like this:
(function($){
	$.fn.defaultInput = function(){

		return this.each(function(){	
			
		});
	};
})(jQuery);



The line:
$.fn.defaultInput = function(){



Is basically saying this is meant to extend jQuery itself. So we can use the familiar syntax:
   $("#some_element").ourPlugin();



The line:
return this.each(function(){	



Ensures that our plugin returns the element itself so that we can make use of jQuery's powerful method chaining. We can do something like:
   $("#some_element").ourPlugin().slideUp();



This is a good framework for any plugin. You would of course have to replace the $.fn.defaultInput with $.fn.pluginName if you were going to use this for other plugins.

This plugin is going to accept some parameters. A common way of passing parameters to methods in jQuery is to use a Javascript object. It is not uncommon to see something like:
 $("#element").method({
    prop1:"Some property",
    prop2:"Some other property"
  });



Our plugin will accept an object literal as a argument. The object will hold properties that will be used within our plugin. The properties that our plugin will use are:
  • text - The default text for the element
  • active - The class the element will have when the element no longer has the default value
  • inactive - The class the element will have when it has the default value


We will also define defaults for these properties in the event they are not explicitly set.

Make the following modifications to your code:
(function($){
	$.fn.defaultInput = function(options){
                //default properties for plugin
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};

		var options = $.extend(defaults,options);

		return this.each(function(){	
			
		});
	};
})(jQuery);



As you can see our method now has a parameter, options. The lines:
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};


Create a Javascript object with three properties. These are the default values for our plugin. The line:
var options = $.extend(defaults,options);



Makes use of the jQuery method extend. This method merges the contents of objects together. The first argument is the base object, the second argument is an object that will be merged with the first. If a property of the same name exists in both then the second objects properties will overwrite the first. For example, the following:
 var obj1 = {
      prop1:"obj1 prop1",
      prop2:"obj1 prop2"  
     }

 var obj2 = {
      prop1:"obj2 prop1"
     }

 var obj3 = $.extend(obj1 ,obj2 );



Would result in:
   alert(obj3.prop1); // "obj2 prop1"
   alert(obj3.prop2); // "obj1 prop1"



So now that we have the ability to pass an argument to our plugin, it's time to implement the functionality. Change your code to the following:
(function($){
	$.fn.defaultInput = function(options){
                //default properties for plugin
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};

		var options = $.extend(defaults,options);

		return this.each(function(){
                        //set the default text value and add the inactive class.	
			$(this).val(options.text).
			addClass(options.inactive);			
		});
	};
})(jQuery);



The lines:
$(this).val(options.text).
addClass(options.inactive);	


Set the elements value to the default text and give the element the specified class for inactive elements.

Now add the changes:
(function($){
	$.fn.defaultInput = function(options){
                //default properties for plugin
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};

		var options = $.extend(defaults,options);

		return this.each(function(){
                        //set the default text value and add the inactive class.	
			$(this).val(options.text).
			addClass(options.inactive);	
			
                       $(this).focus(function(){
				if($(this).val() == options.text)
				{
					$(this).val("").
					removeClass(options.inactive).
					addClass(options.active);					
				}
			
			});
		
		});
	};
})(jQuery);



The lines:
$(this).focus(function(){
	if($(this).val() == options.text)
	{
		$(this).val("").
		removeClass(options.inactive).
		addClass(options.active);					
	}
			
});



This attaches an event listener to the focus event of the element. If the value of the element is equal to our default value passed in, we clear the element's value, remove the inactive class from the element and add the active class.

Next we add our listener for the blur event:
(function($){
	$.fn.defaultInput = function(options){
                //default properties for plugin
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};

		var options = $.extend(defaults,options);

		return this.each(function(){
                        //set the default text value and add the inactive class.	
			$(this).val(options.text).
			addClass(options.inactive);	
			
                       $(this).focus(function(){
				if($(this).val() == options.text)
				{
					$(this).val("").
					removeClass(options.inactive).
					addClass(options.active);					
				}
			
			});

			$(this).blur(function(){
				if($(this).val() == "")
				{
					$(this).val(options.text).
					removeClass(options.active).
					addClass(options.inactive);
				}
			});
		
		});
	};
})(jQuery);



The lines:
$(this).blur(function(){
	if($(this).val() == "")
	{
		$(this).val(options.text).
		removeClass(options.active).
		addClass(options.inactive);
	}
});



Attach a listener for the blur event. When the element loses focus if nothing has been entered, the element's value returns to the default, the specified active class is removed and the inactive class is added.

This is now a functioning plugin! You could make a call to this plugin with the following code:
   <form>
      <input type = "text" name = "first_name" id = "first_name" />
      <input type = "text" name = "last_name" id = "last_name" />
   </form>

<script type = "text/javascript">
$(function(){
  $("#first_name").defaultInput({
        text:"Enter First Name Here",
        active:"active_input",
        inactive:"inactive_input"
   });

  $("#last_name").defaultInput({
        text:"Enter Last Name Here",
        active:"active_input",
        inactive:"inactive_input"
   });

});
</script>



That should result in the first_name input having the value of "Enter First Name Here" and the class "inactive_input" and the last_name input having the value of "Enter Last Name Here" and the class "inactive_input".

In an effort to make our plugin a bit more streamlined lets give it the option of only passing a string as an argument. This will be used as the default text value for our element and it will automatically use the default active and inactive classes. The final code looks like this:
(function($){
	$.fn.defaultInput = function(options){
         //if a string is passed in assign it to the text property of an object called options
		if(typeof options == "string")
		{
			options = {text:options};
		}

        //default properties for plugin
		var defaults = {
			text:"",
			active:"txtActive",
			inactive:"txtInactive"
		};
         //merge the default options with those passed in
		var options = $.extend(defaults,options);

		return this.each(function(){
             //set the default text value and add the inactive class.	
			$(this).val(options.text).
			addClass(options.inactive);	
		     //when element gets focus
             $(this).focus(function(){
                //if element has only default text, remove it and apply the active class to the element
                //while removing the inactive class
				if($(this).val() == options.text)
				{
					$(this).val("").
					removeClass(options.inactive).
					addClass(options.active);					
				}
			
			});

            //when this element loses focus
			$(this).blur(function(){
                //if nothing was entered by the user return the default input. Remove active class and
                // add inactive class
				if($(this).val() == "")
				{
					$(this).val(options.text).
					removeClass(options.active).
					addClass(options.inactive);
				}
			});
		
		});
	};
})(jQuery);



The lines:
if(typeof options == "string")
{
	options = {text:options};
}



Checks to see if a string has been passed in as the argument, if so the string is assigned to the text property of an object named options. This will result in the string being used as the default text value of the element and the inactive and active classes will be the plugins default values.

To illustrate this, changing our example usage from earlier:
   <form>
      <input type = "text" name = "first_name" id = "first_name" />
      <input type = "text" name = "last_name" id = "last_name" />
   </form>

<script type = "text/javascript">
$(function(){
  $("#first_name").defaultInput({
        text:"Enter First Name Here",
        active:"active_input",
        inactive:"inactive_input"
   });

  $("#last_name").defaultInput("Enter Last Name Here");

});
</script>



Would result in the first_name element having the value of "Enter First Name Here" and the class "inactive_input" as before. The last_name element would have the value "Enter Last Name Here" and the class "txtInactive", which is the plugins default value.

This concludes the tutorial. Thanks for reading, I hope you found it informative and useful. I have provided an attachment that contains a small one page project that demonstrates this plugin's usage. I suggest downloading it and checking it out if you would like to get a better understanding of how this works.

Any comments, questions and feedback are welcome. I will do my best to respond in kind.

Thanks again for reading!

Edit: It has been brought to my attention by Dormilich that HTML5 supports a placeholder attribute for inputs that can duplicate this functionality. You can read about this in a tutorial by EnvXOwner found here.

Attached File(s)


This post has been edited by Jstall: 26 September 2011 - 06:28 AM


Is This A Good Question/Topic? 1
  • +

Replies To: jQuery default input value plugin

#2 JackOfAllTrades  Icon User is online

  • Saucy!
  • member icon

Reputation: 5951
  • View blog
  • Posts: 23,212
  • Joined: 23-August 08

Posted 23 September 2011 - 11:46 AM

Great job, dude!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1