Friday, 13 December 2013

Convert Amount in numbers to words in JavaScript

 <asp:TextBox ID="txtsumassured" runat="server" MaxLength="15"                                       onkeyup="AN_toWords(this.value, 'lblnumtoword', 'lblerrsumass', 'Imgerriconsumass')></asp:TextBox>



//----------It is not applicable for More than 15 digits ---------------------------//
function AN_toWords(MyVal, lblnumbertoword, errmess, erricon) {
    document.getElementById(lblnumbertoword).innerHTML = "";
    var rVal = MyVal;
    var numbers = /^[0-9\,]+$/;
    MyVal = MyVal.toString();
    MyVal = MyVal.replace(/[\, ]/g, '');
    var tempnew = MyVal;
    if (tempnew == "") {
        document.getElementById(errmess).innerHTML = "Please enter the single premium";
        return false;
    }
    else if (!numbers.test(tempnew)) {
        document.getElementById(errmess).innerHTML = "Please enter a valid amount";
            return false;
        }

    rVal = Math.floor(tempnew);
    var rup = new String(rVal);

    rupRev = rup.split("");
    actualNumber = rupRev.reverse();

    if (Number(rVal) >= 0) {

    }
    else {
        alert('Number cannot be converted');
        return false;
    }
    if (Number(rVal) == 0) {
        document.getElementById(lblnumbertoword).innerHTML = 'Zero Only';
        return false;
    }


    var numWords = ["Zero", " One", " Two", " Three", " Four", " Five", " Six", " Seven", " Eight", " Nine"];
    var numPlace = ['Ten', ' Eleven', ' Twelve', ' Thirteen', ' Fourteen', ' Fifteen', ' Sixteen', ' Seventeen', ' Eighteen', ' Nineteen'];
    var tPlace = ['dummy', ' Ten', ' Twenty', ' Thirty', ' Forty', ' Fifty', ' Sixty', ' Seventy', ' Eighty', ' Ninety'];

    var numWordsLength = rupRev.length;
    var totalWords = "";
    var numtoWords = new Array();
    var finalWord = "";
    j = 0;
    for (i = 0; i < numWordsLength; i++) {
        switch (i) {
            case 0:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                numtoWords[j] = numtoWords[j] + ' Only';
                break;
            case 1:
                CTen();
                break;
            case 2:
                if (actualNumber[i] == 0) {
                    numtoWords[j] = '';
                }
                else if (actualNumber[i - 1] != 0 && actualNumber[i - 2] != 0) {
                    numtoWords[j] = numWords[actualNumber[i]] + ' Hundred and';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]] + ' Hundred';
                }
                break;
            case 3:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                    numtoWords[j] = numtoWords[j] + " Thousand";
                }
                break;
            case 4:
                CTen();
                break;
            case 5:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                    numtoWords[j] = numtoWords[j] + " Lakh";
                }
                break;
            case 6:
                CTen();
                break;
            case 7:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                numtoWords[j] = numtoWords[j] + " Crore";
                break;
            case 8:
                CTen();
                break;
            case 9:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                    numtoWords[j] = numtoWords[j] + " Hundred ";
                }
                break;
            case 10:
                CTen();
                break;
            case 11:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                    numtoWords[j] = numtoWords[j] + " Thousand ";
                }
                break;
            case 12:
                CTen();
                break;
            case 13:
                if (actualNumber[i] == 0 || actualNumber[i + 1] == 1) {
                    numtoWords[j] = '';
                }
                else {
                    numtoWords[j] = numWords[actualNumber[i]];
                }
                if (actualNumber[i + 1] != 0 || actualNumber[i] > 0) {
                    numtoWords[j] = numtoWords[j] + " Lakh ";
                }
                break;
            case 14:
                CTen();
                break;
            default:
                break;
        }
        j++;
    }

    function CTen() {
        if (actualNumber[i] == 0) {
            numtoWords[j] = '';
        }
        else if (actualNumber[i] == 1) {
            numtoWords[j] = numPlace[actualNumber[i - 1]];
        }
        else {
            numtoWords[j] = tPlace[actualNumber[i]];
        }
    }
    numtoWords.reverse();
    for (i = 0; i < numtoWords.length; i++) {
        finalWord += numtoWords[i];
    }
    document.getElementById(lblnumbertoword).innerHTML = finalWord;
}


Display State,Based on State City will be Displayed in Jquery(Without Postback)

 <asp:TextBox ID="UC8_AN_txtState" runat="server" CssClass="autosuggest input-style"
                                        Width="150px"></asp:TextBox>

 <asp:TextBox ID="UC8_AN_txtCity" runat="server" CssClass="autosuggest123 input-style"
                                        Width="150px" class="input-style" value="City"></asp:TextBox>

 function SearchState() {
        $(".autosuggest").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Annuity.aspx/GetState", //Call C# Method Gupta
                    data: "{'STATE_Name':'" + document.getElementById('CPH1_ID_AN_AD_Proposal_UC8_AN_txtState').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Error");
                    }
                });
            }
        });
    }

    function Searchcity() {

        $(".autosuggest123").autocomplete({
            source: function (request, response) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "Annuity.aspx/Getcity", //Call C# Method Gupta
                    data: "{'STATE_Name':'" + document.getElementById('CPH1_ID_AN_AD_Proposal_UC8_AN_txtState').value + "','city_NAME':'" + document.getElementById('CPH1_ID_AN_AD_Proposal_UC8_AN_txtCity').value + "'}",
                    dataType: "json",
                    success: function (data) {
                        response(data.d);
                    },
                    error: function (result) {
                        alert("Errorcity");
                    }
                });
            }
        });
    }


 [WebMethod]
    public static List<string> GetState(string STATE_Name)
    {
        List<string> result = new List<string>();
        OracleConnection objConn = new OracleConnection();
        objConn.ConnectionString = ConfigurationManager.ConnectionStrings["ora"].ToString();
        OracleConnection connection = new OracleConnection(objConn.ConnectionString);
        OracleCommand cmd = new OracleCommand("select STATE_NAME FROM m_eion_state  where lower(STATE_NAME) like '" + STATE_Name.ToLower() + "%'");
        cmd.Connection = connection;
        connection.Open();
        cmd.ExecuteNonQuery();
        OracleDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            result.Add(dr["STATE_NAME"].ToString());
        }
        return result;
    }


    [WebMethod]
    public static List<string> Getcity(string STATE_Name, string city_NAME)
    {
        List<string> result = new List<string>();
        OracleConnection objConn = new OracleConnection();
        objConn.ConnectionString = ConfigurationManager.ConnectionStrings["ora"].ToString();
        OracleConnection connection = new OracleConnection(objConn.ConnectionString);
        OracleCommand stateid = new OracleCommand("select STATE_ID from m_eion_state where state_name = '" + STATE_Name + "'");
        stateid.Connection = connection;
        connection.Open();
        int stateId = Convert.ToInt32(stateid.ExecuteScalar());
        OracleCommand cmd = new OracleCommand("select CITY_NAME FROM m_eion_city  where Lower(CITY_NAME) like '" + city_NAME.ToLower() + "%' and STATE_ID = '" + stateId + "'");
        cmd.Connection = connection;
        cmd.ExecuteNonQuery();
        OracleDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            result.Add(dr["CITY_NAME"].ToString());
        }
        return result;
    }

Download File From Website

 string strURL = @"~/DownloadFiles/Form 60.pdf";
            string Name = "Form 60.pdf";
            WebClient req = new WebClient();
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.ClearContent();
            response.ClearHeaders();
            response.Buffer = true;
            response.AddHeader("Content-Disposition", "attachment;filename=\"" + Name + "\"");
            byte[] data = req.DownloadData(Server.MapPath(strURL));
            response.BinaryWrite(data);
            response.End();

Thursday, 22 August 2013

JQuery Effects:

Showing and Hiding elements:

The commands for showing and hiding elements are pretty much what we would expect: show()to show the elements in a wrapped set and hide() to hide them.

Syntax:

Here is the simple syntax for show() method:
[selector].show( speed, [callback] );
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.
Following is the simple syntax for hide() method:
[selector].hide( speed, [callback] );
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

Consider the following HTML file with a small JQuery coding:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">
   
   $(document).ready(function() {

     $("#show").click(function () {
        $(".mydiv").show( 1000 );
     });

     $("#hide").click(function () {
        $(".mydiv").hide( 1000 );
     });

   });

   </script>
   <style>
   .mydiv{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:100px;
    }
  </style>
</head>
<body>
   <div class="mydiv">
      This is  SQUAR
   </div>

   <input id="hide" type="button" value="Hide" />   
   <input id="show" type="button" value="Show" />   

</body>
</html>
To understand it in better way you can Try it yourself.

Toggling the elements:

jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown.

Syntax:

Here is the simple syntax for one of the toggle() methods:
[selector]..toggle([speed][, callback]);
Here is the description of all the parameters:
  • speed: A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).
  • callback: This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against.

Example:

We can animate any element, such as a simple <div> containing an image:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $(".clickme").click(function(event){
          $(".target").toggle('slow', function(){
             $(".log").text('Transition Complete');
          });
      });

   });
   </script>
   <style>
   .clickme{ margin:10px;padding:12px;
      border:2px solid #666;
      width:100px;
      height:50px;
    }
   </style>
</head>
<body>
   <div class="content">
      <div class="clickme">Click Me</div>
      <div class="target">
         <img src="/images/jquery.jpg" alt="jQuery" />
      </div>
      <div class="log"></div>
</body>
</html>
To understand it in better way you can Try it yourself.

JQuery Effect Methods:

You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects:
Methods and Description
animate( params, [duration, easing, callback] )
A function for making custom animations.
fadeIn( speed, [callback] )
Fade in all matched elements by adjusting their opacity and firing an optional callback after completion.
fadeOut( speed, [callback] )
Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion.
fadeTo( speed, opacity, callback )
Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion.
hide( )
Hides each of the set of matched elements if they are shown.
hide( speed, [callback] )
Hide all matched elements using a graceful animation and firing an optional callback after completion.
show( )
Displays each of the set of matched elements if they are hidden.
show( speed, [callback] )
Show all matched elements using a graceful animation and firing an optional callback after completion.
slideDown( speed, [callback] )
Reveal all matched elements by adjusting their height and firing an optional callback after completion.
slideToggle( speed, [callback] )
Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion.
slideUp( speed, [callback] )
Hide all matched elements by adjusting their height and firing an optional callback after completion.
stop( [clearQueue, gotoEnd ])
Stops all the currently running animations on all the specified elements.
toggle( )
Toggle displaying each of the set of matched elements.
toggle( speed, [callback] )
Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion.
toggle( switch )
Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements).
jQuery.fx.off
Globally disable all animations.

UI Library Based Effects:

To use these effects you would have to download jQuery UI Library jquery-ui-1.7.2.custom.min.js or latest version of this UI library from jQuery UI Library.
After extracting jquery-ui-1.7.2.custom.min.js file from the download, you would include this file in similar way as you include core jQuery Library file.
Methods and Description
Blind
Blinds the element away or shows it by blinding it in.
Bounce
Bounces the element vertically or horizontally n-times.
Clip
Clips the element on or off, vertically or horizontally.
Drop
Drops the element away or shows it by dropping it in.
Explode
Explodes the element into multiple pieces.
Fold
Folds the element like a piece of paper.
Highlight
Highlights the background with a defined color.
Puff
Scale and fade out animations create the puff effect.
Pulsate 
Pulsates the opacity of the element multiple times.
Scale
Shrink or grow an element by a percentage factor.
Shake
Shakes the element vertically or horizontally n-times.
Size
Resize an element to a specified width and height.
Slide 
Slides the element out of the viewport.
Transfer
Transfers the outline of an element to another.

JQuery DOM Traversing Methods:


Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements:
SelectorDescription
eq( index )Reduce the set of matched elements to a single element.
filter( selector )Removes all elements from the set of matched elements that do not match the specified selector(s).
filter( fn )Removes all elements from the set of matched elements that do not match the specified function.
is( selector )Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector.
map( callback )Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements).
not( selector )Removes elements matching the specified selector from the set of matched elements.
slice( start, [end] )Selects a subset of the matched elements.
Following table lists down other useful methods which you can use to locate various elements in a DOM:
SelectorDescription
add( selector )Adds more elements, matched by the given selector, to the set of matched elements.
andSelf( )Add the previous selection to the current selection.
children( [selector])Get a set of elements containing all of the unique immediate children of each of the matched set of elements.
closest( selector )Get a set of elements containing the closest parent element that matches the specified selector, the starting element included.
contents( )Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe.
end( )Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state .
find( selector )Searches for descendent elements that match the specified selectors.
next( [selector] )Get a set of elements containing the unique next siblings of each of the given set of elements.
nextAll( [selector] )Find all sibling elements after the current element.
offsetParent( )Returns a jQuery collection with the positioned parent of the first matched element.
parent( [selector] )Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements.
parents( [selector] )Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element).
prev( [selector] )Get a set of elements containing the unique previous siblings of each of the matched set of elements.
prevAll( [selector] )Find all sibling elements in front of the current element.
siblings( [selector] )Get a set of elements containing all of the unique siblings of each of the matched set of elements.

Useful Attribute Methods in JQuery:


Following table lists down few useful methods which you can use to manipulate attributes and properties:
MethodsDescription
attr( properties )Set a key/value object as properties to all matched elements.
attr( key, fn )Set a single property to a computed value, on all matched elements.
removeAttr( name )Remove an attribute from each of the matched elements.
hasClass( class )Returns true if the specified class is present on at least one of the set of matched elements.
removeClass( class )Removes all or the specified class(es) from the set of matched elements.
toggleClass( class )Adds the specified class if it is not present, removes the specified class if it is present.
html( )Get the html contents (innerHTML) of the first matched element.
html( val )Set the html contents of every matched element.
text( )Get the combined text contents of all matched elements.
text( val )Set the text contents of all matched elements.
val( )Get the input value of the first matched element.
val( val )Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked.
Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation:
  • $("#myID").attr("custom") : This would return value of attribute custom for the first element matching with ID myID.
  • $("img").attr("alt", "Sample Image"): This sets the alt attribute of all the images to a new value "Sample Image".
  • $("input").attr({ value: "", title: "Please enter a value" }); : Sets the value of all <input> elements to the empty string, as well as sets the title to the string Please enter a value.
  • $("a[href^=http://]").attr("target","_blank"): Selects all links with an href attribute starting with http:// and set its target attribute to _blank
  • $("a").removeAttr("target") : This would remove target attribute of all the links.
  • $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); : This would modify the disabled attribute to the value "disabled" while clicking Submit button.
  • $("p:last").hasClass("selected"): This return true if last <p> tag has associated classselected.
  • $("p").text(): Returns string that contains the combined text contents of all matched <p> elements.
  • $("p").text("<i>Hello World</i>"): This would set "<I>Hello World</I>" as text content of the matching <p> elements
  • $("p").html() : This returns the HTML content of the all matching paragraphs.
  • $("div").html("Hello World") : This would set the HTML content of all matching <div> to Hello World.
  • $("input:checkbox:checked").val() : Get the first value from a checked checkbox
  • $("input:radio[name=bar]:checked").val(): Get the first value from a set of radio buttons
  • $("button").val("Hello") : Sets the value attribute of every matched element <button>.
  • $("input").val("on") : This would check all the radio or check box button whose value is "on".
  • $("select").val("Orange") : This would select Orange option in a dropdown box with options Orange, Mango and Banana.
  • $("select").val("Orange", "Mango") : This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana.

Applying Styles in JQuery


The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space.

Example:

Following is a simple example which set src attribute of an image tag to a correct location:
<html>
<head>
<title>the title</title>
   <script type="text/javascript" 
   src="/jquery/jquery-1.3.2.min.js"></script>
   <script type="text/javascript" language="javascript">

   $(document).ready(function() {
      $("em").addClass("selected");
      $("#myid").addClass("highlight");
   });

   </script>
   <style>
      .selected { color:red; }
      .highlight { background:yellow; }
  </style>
</head>
<body>
   <em title="Bold and Brave">This is first paragraph.</em>
   <p id="myid">This is second paragraph.</p>
</body>
</html>