Banner Ad

Monday, April 14, 2014

JQuery Tips and Tricks #1–Simple Addition using JQuery

By Francis   Posted at   5:51 AM   JQuery Tips No comments
                                In this post we are going to see a simple addition of 2 numbers using JQuery. Copy and paste the below code:



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="JQuery1_11.js" type="text/javascript"></script>
    <script language="javascript" type="text/javascript">
        // Check that all document objects are loaded
        $(document).ready(function () {
            // Attach click event to the "button" object
            $('#submitbutton').click(function () {
                // get first no
                var firstNo = $("#txtFirstNo").val();
                // get second no
                var secondNo = $("#txtSecondNo").val();
                // Convert the input as integer and sum up them
                var result = parseInt(firstNo,10) + parseInt(secondNo,10);
                $("#txtResult").val(result);
            })
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:TextBox runat="server" ID="txtFirstNo"></asp:TextBox> +
            <asp:TextBox runat="server" ID="txtSecondNo"></asp:TextBox> =
            <asp:TextBox runat="server" ID="txtResult"></asp:TextBox>
            <asp:Button runat="server"  ID="submitbutton"  Text="Sum"/>
        </div>
    </form>
</body>
</html>


In the first line, we include the JQuery script file, we can download the same from this url.

In the above code we have used the following JQuery functions:
ready() – check that DOM elements are loaded.
click() – attach click event to the respective element, here button
val() – Function get/sets value from/to the text box.

Also I have used the javascript function “parseInt”,  which converts the string into an integer (here we have changed the string into Decimal value, that’s why the radix value given as 10).
After entering values in both textboxes when click the “Sum” button, the sum will be displayed in “txtResult” textbox.
Output:

JQuery-Simple_Addition
If you have any thoughts please let me know your thoughts in comments!!

About Francis

Francis, an Associate at Cognizant. Having 7+ Years of experience in Microsoft web technologies.

0 comments :

Please give your valuable comments to improve the contents

Connect with Us