How to Create Jquery Plugin for Input Currency

Seegatesite.com – Jquery has become a major requirement for web developers. Jquery provide thousands of plugins that can be implemented on our website more attractive and dynamic. Jquery itself has the task to manipulate the DOM and traditional Javascript which fairly complex to be more concise. In this article I will provide a tutorial how to create jquery plugin for your own needs, which can help accelerate the development of your own website’s application.

How To Create Jquery Plugin For Input Currency

JQuery plugin is one of jQuery features that provide extensibility in the development of jQuery. Someone could create a plugin to suit their needs and can be distribute them broadly in line with the standards set by jQuery Foundation. By building a jQuery plugins, you have participated in contributing to developing better jQuery.

In this tutorial we will create a feature called “currency” a jQuery plugin that can perform input for currency manipulation. What we’ll do is ignore a character string into a number and leave the currency format.

Create Currency Jquery Plugin

To create a jquery plugin, we require encapsulation for plugin first. Encapsulation jquery plugin has a structure like the following code

(function($){

    // Your jquery code

})(jQuery);

Then you be able to create a function with any name you need. This time we will create a function called “currency“. By calling $ .fn you’ve added a function called “currency” in jQuery.

(function($){

   $.fn.currency = function()
    {
	        
    };

})(jQuery);

We will create jquery plugin with the following features

  1. Eliminating non-numerical characters (“0 – 9” , “.” , “-“).
  2. Change the value to the currency format in the blur event .
  3. When the input gets focus, jquery will select the entire value (block selection).
  4. Add new css property text-align: right.

Let’s add code so the jquery plugin can be run in accordance with the above features

/*
author : sigit prasetya nugroho
url : http://seegatesite.com
*/
(function($){

   $.fn.currency = function()
    {
        $(this).css("text-align", "right");

        function addCommas(nStr)
        {
        	nStr += '';
        	x = nStr.split('.');
        	x1 = x[0];
        	x2 = x.length > 1 ? '.' + x[1] : '';
        	var rgx = /(\d+)(\d{3})/;
        	while (rgx.test(x1)) {
        		x1 = x1.replace(rgx, '$1' + ',' + '$2');
        	}
        	return x1 + x2;
        }

        function cleanString(str) 
        {	
	       return str.replace(/[^0-9.-]/g, "");
	}

	$(this).blur(function() {
		var number=parseFloat(cleanString($(this).val()));
		if(number ==''){
			$(this).val(0);	
		}else{
		if(isNaN(number))
		{
		   number=0;
		}
		$(this).val('Rp '+addCommas(number));	
		}
	});
	$(this).focus(function(e){
		$(this).val(cleanString($(this).val()));
		if(e.which === 9){
                      return false;
		}
		$(this).select();
	});
    };

})(jQuery);

Save the script as currency.js

Explanation :

  • $(this).css("text-align", "right"); – Code to add css property such as text-align with “right” value.
  • function addCommas(nStr){ } – Function to add delimiter commas and sign “.” to numbers.
  • function cleanString(str){ } – Function to clean up the string in addition to the symbol numbers “0-9”, “.” and “,”.
  • $(this).blur(function(){ ... } – The main role of the plugins contained in this line of code. When the cursor no longer focused on the input box, blur event is run. Jquery will perform check and add the word ‘Rp’ at the beginning of the string as a currency symbol, as a symbol of my country’s currency is Rupiah (Rp).
  • $(this).focus(function(e){ .. } – The role of the focus event is when the cursor focus on the input box, then jquery will eliminate all the attributes other than numbers and will select the entire string to easier for users change the value of the input box

The main part of jquery plugin has been created, to try it out please create an index.html file and copy the following code

<html>
<head>
    <title>Currency Jquery Plugin</title>
</head>
<body>
<h3>Learn to create jquery plugins to manipulate currency data in the input box html</h3>
<label>Earning : </label><input type="text" style="width:200px" id="textmoney" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript" src="currency.js"></script>
<script>
    $("#textmoney").currency();
</script>
</body>
</html>

Finish, now we can use our plugin with this simple code below

$("#textmoney").currency();

Added option in jquery plugin

jQuery plugin is very dynamic, we could add the option in jquery plugin as much. We will attempt to add the currency symbol on the plugin. Add the following line of code :

$(this).css("text-align", "right");

        var opts = {
            symbol : "Rp ",
        };

        var opts = $.extend(opts, settings);

Then change the function of the blur event as follows

$(this).blur(function() {
			var number=parseFloat(cleanString($(this).val()));
			if(number ==''){
				$(this).val(0);	
			}else{
				if(isNaN(number))
				{
					number=0;
				}
				$(this).val(opts.symbol+addCommas(number));	
			}
		});

Then call the plugin on the index.html with the following code

$("#textmoney").currency({'symbol':'$ '});

How To Create Jquery Plugin For Input Currency EasyNow run the script and see the result. Easy, right? If you want the source code please download the link below

Thus article about How to Create Jquery Plugin for Input Currency , hope useful 🙂

The following two tabs change content below.
This site is a personal Blog of Sigit Prasetya Nugroho, a Desktop developer and freelance web developer working in PHP, MySQL, WordPress.

Leave a Comment

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

%d bloggers like this: