Sunday, May 31, 2015

Make your own Spinner Control

Today, we will see how to make our own spinner control using jQuery and CSS.

First of all, we need to place a button and textbox controls on our HTML page under the <body> and <form> section like this:

    <table cellpadding="2" cellspacing="2" width="100%">
        <tr>
                <td align="center">
                <input type="button" id="plus" value="+" runat="server" />
        </td>
        </tr>
        <tr>
        <td align="center">
                <input type="text" id="mybox" value="0" size="1" />
        </td>
        </tr>
        <tr>
                <td align="center">
                <input type="button" id="minus" value="-" runat="server" />
        </td>
        </tr>
    </table>


Then, we need to include the reference of latest jQuery file like this in <head> section:

<script src="//code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>

After this, add the below script of jQuery in <head> section like this:

<script type="text/javascript">
        $(document).ready(function () {

            $("#plus").click(function () {

                var myvalue = $("#mybox").val();

                if (myvalue == '0') {
                    myvalue = parseInt(1);
                }
                else {
                    myvalue = parseInt(myvalue);
                    if (myvalue < 10) {
                        myvalue = myvalue + 1;
                    }
                    else {
                        myvalue = 10;
                    }
                }

                $("#mybox").val(myvalue);
            });

            $("#minus").click(function () {

                var myvalue = $("#mybox").val();
                if (myvalue == '') {
                    myvalue = parseInt(0);
                }
                else {
                    myvalue = parseInt(myvalue);
                    if (myvalue > 1) {
                        myvalue = myvalue - 1;
                    }
                    else {
                        myvalue = 0;
                    }
                }

                $("#mybox").val(myvalue);
            });

        });
    </script>

Now, run this code on any browser. You can also apply the CSS to make this more interactive and presentable.