Sunday, May 11, 2014

Creating a JQuery Plugin

Hi Readers

This post is about creating a plugin using JQuery.
You may have used many plugins that are developed using jquery and wondered how they are developed,

I expect you to know the basics of jqurey to understand this post but will make it as simple as possible.

This post will explain how to create a simple textbox which is a readonly textbox and getting and setting the value will be done via the methods that we create, there is a method to reset the value as well.

Now lets see the coding, all explanations are given as comments.

// Option gets the option settings or the function name
// value is to get the value for setters
$.fn.CustomTextBox = function (option, value) {

    // If options are passed then initialize the textbox
    if (typeof (option) == 'object') {
        //Append the textbox
        //its recommended that you put a class name so that its easy for styling
        $(this).append("<input readonly="" type="text" value="" + option.Text + "" />");
        //Store the default value in the data so that it can be accessed later
        //This method can be used to store the server urls and other setting which needed
        //to be accessed later
        $(this).data("Default", option.Text);
    }
    // If a string is passed its assumed that it a method call
    else {
        //Switch the method based on the string passed
        switch (option) {

            case "Set":
                //If its set then set the value of the textbox
                $(this).find("input").val(value);
                break;
            case "Get":
                //If its get the return the value of the textbox
                return $(this).find("input").val();
                break
            case "Reset":
                //if its reset the get the default value from the data variable and 
                //set it to the textbox
                $(this).find("input").val($(this).data("Default"));
                break;
        }
    }
}

$(document).ready(function () {
    //Initialize the textbox
    $("#container").CustomTextBox({ Text: "Default Text" });

    $("#btnSetValue").click(function () {
        //set the value of the text box
        $("#container").CustomTextBox('Set', "New Value");
    });

    $("#btnGetValue").click(function () {
        //get the value of the text box and alert it
        alert($("#container").CustomTextBox('Get'));
    });

    $("#btnResetValue").click(function () {
        //reset the value of the text box
        $("#container").CustomTextBox('Reset');
    });
});

Now lets see the html section
<div id="container">
</div>
<input type="button" id="btnSetValue" value="Set Value" />
<input type="button" id="btnGetValue" value="Get Value" />
<input type="button" id="btnResetValue" value="Reset Value" />

So thats how you create a simple Jquery plugin.
Happy Coding :)
-Guru-

No comments:

Post a Comment