Saturday, 4 January 2014

How to Find, Replace and Highlight a word using Jquery?

Description:

In this article, I will explain how to find, replace and highlight a word using Jquery.  

To find occurrence of string use match() method.

Syntax:

string.match(regularexpression)

match() used to search string with the regular expression and it will return only the first match in the string

If no match is found, it will return null value.

If the word matches with the target string, some action will happen based on your requirement.

To replace the string with new value use replace() method.

Syntax:

string.replace(searchvalue, targetstring)

replace() method used to searches string with the regular expression and it will return the new string where the string values are replaced.

To highlight a word, add style property with the target values.

The below example program will explain how to find, replace and highlight a word using Jquery.

Example Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var searchblock = ['p'];
            $("#TextBox1").bind('keyup', function (e) {
                var findtext = $("#TextBox1").val();
                $.each(searchblock, function (i) {
                    var Wholetexts = $('p').text();
                    Wholetexts = Wholetexts.replace(findtext, function (e) {
                        return "<span style='background-color: gray;'>" + e + "</span>";
                    });
                    $('p').html(Wholetexts);
                });
            });
            $("#btnReplace").click(function () {
                var find = $('#TextBox1').val();
                var replacewith = $('#TextBox2').val();
                $('p').html($('p').html().replace(find, replacewith));
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            This is the sample text for find and replace example</p>
        <asp:Label ID="Label1" runat="server" Text="Find"></asp:Label>
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        <asp:Label ID="Label2" runat="server" Text="Replace With"></asp:Label>
        <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
        <br />
        <input id="btnReplace" type="button" value="Replace" />
    </div>
    </form>
</body>
</html>

Highlight a word with jQuery, Highlighting search words with jQuery, Search & Highlight using JQuery, Find and Replace with JQuery, Highlight search terms, Use jQuery to find and replace multiple words on the page

How to convert Lowercase string to Uppercase using Jquery?

Description:

In this article, I will explain how to convert string to uppercase using Jquery.

toUpperCase() method is used to convert a string into uppercase.

toLowerCase() method is used to convert a string into lowercase.

We can bind this method with text box KeyUp() event. When user types anything, this method will change the text box value into uppercase or lowercase with each keystroke.

We can also convert first letter of each word to uppercase.


Example Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#txtUpper').keyup(function () {
                this.value = this.value.toUpperCase();
            });
            $('#txtLower').keyup(function () {
                this.value = this.value.toLowerCase();
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lbltext" runat="server" Text="Enter Text:"></asp:Label>
        <asp:TextBox ID="txtUpper" runat="server"></asp:TextBox>
        <asp:TextBox ID="txtLower" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

Lowercase and Uppercase with jQuery, Convert lowerCase to upperCase using jquery, Convert to upper case while typing, How to change a string into uppercase, Change text box value in uppercase or lowercase using jQuery

How to call server side methods using Ajax Call?

Description:

In this article, I will explain how to call server side methods using Jquery.

We can call server side methods using JQuery Ajax.

Ajax allows you to load data in the background and updates on the webpage without refreshing the page.

Ajax used to create fast and dynamic web pages.

The user can continue to interact with the web page while the page requests information from the server with Ajax in the background.

Syntax for Ajax Call:

$.ajax({
            type: "POST",
            url: "AjaxCall.aspx/CallServerSideMethod",
            data: "{'args': '" + arguments + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(response) {
            },
            error: function() {
            }
        });

Type Type of the request. Default is GET. Possible types are GET, POST, and PUT.

Url Redirecting the page to which the request is sent

Data Passing parameters for the methods. It should be key/value pairs.

DataType Type of data which is returned from the server. Possible data types are xml, json, script, text and html.

Success This function will call if the request succeeds.

Error This function will call if the request fails.

AJAX – Example Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Sample Ajax Call</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnAjaxCall').click(function () {
                var arguments = "www.jqueryjohn.com";

                $.ajax({
                    type: "POST",
                    url: "Ajaxcall.aspx/CallServerSideMethod",
                    data: "{'args': '" + arguments + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        alert(response.d);
                        return false;
                    },
                    error: function () {
                        alert("error");
                    }
                });
                return false;
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lbltext" runat="server" Text="Click the button to make Ajax Call"></asp:Label>
        <asp:Button ID="btnAjaxCall" runat="server" Text="Make Ajax Call" />
        <br />
    </div>
    </form>
</body>
</html>

Code Behind:

Two things are very important while we creating ajax call

1. Method should be declared as WebMethod
2. Method should be static

[System.Web.Services.WebMethod]
public static string CallServerSideMethod(string args)
{
      return "Welcome to " + args + " ";
}


Calling server side method with AJAX, Invoke Server Methods From Client Side Using jQuery AJAX in ASP.NET, How to make Ajax Call using Jquery, Simple Ajax Call using Jquery, Calling server side method from client side using Jquery, Syntax for Ajax Call in Jquery.

How to check Username Availability using Jquery and Ajax?

Description:

In this article, I will explain how to check username availability using Jquery.

Username Availability Indication becomes really useful part of registration form.

We have to write a code to check whether a username is already been taken or not yet.

When the user starts typing username, keyup() method will be fired and it will call Ajax method for each keystroke.

In the following example, I have created a procedure to find whether the entered username is exists or not.

If the entered data not matches with the database values, it will return indication as “Available”.

If the data exists in database values, it will return indication as “Username already Taken”.

Steps:

1. Create a table 'register'

create table register(UName varchar(30), Pwd varchar(30))
insert into register values('john','jquery');

2. Create a strored procedure to find the existence of user

Create procedure SP_CheckUser 
(@Input_Name varchar(30)) 
as 
begin 
if exists(select 1 from register where uname =@Input_Name ) 
select 1 
else  
select 0 
end

3. Call the Ajax function for keyup event.

Program:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   <scripttype="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
    <scripttype="text/javascript">
        $(document).ready(function () {
            $('#txtUsrName').keyup(function () {
                Var username = $('#txtUsrName').val();

                $.ajax({
                    type: "POST",
                    url: "AjaxCheckUser.aspx/FindExistence",
                    data: "{'args': '" + username + "'}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (response) {
                        if (response.d == 'Taken') {
                            $('#lblUsrNameStatus')[0].innerHTML = "User Name Already Taken";
                        }
                        else {
                            $('#lblUsrNameStatus')[0].innerHTML = "User Name Available";
                        }
                    }
                });
            });
        });
    </script>
</head>
<body>
    <formid="form1"runat="server">
    <div>
        <asp:Label ID="lblUsrName" runat="server" Text="Select User Name:"></asp:Label>
        <asp:TextBox ID="txtUsrName" runat="server"></asp:TextBox>
        <asp:Label ID="lbltext" runat="server" Text="(Existing User Name:john)"></asp:Label>
        <br />
        <asp:Label ID="lblUsrNameStatus" runat="server" Text=""></asp:Label>
    </div>
    </form>
</body>
</html>

Code Behind:

Two things are very important while we creating ajax call

1. Method should be declared as WebMethod
2. Method should be static

        [System.Web.Services.WebMethod]
        public static string FindExistence(string args)
        {
            String UserStatus = string.Empty;
            SqlConnection con = new SqlConnection("Data Source=----;Initial Catalog=TestDatabase;User ID=userid;Password=pwd;");
            SqlCommandcmd = new SqlCommand("SP_CheckUser", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@Input_Name", args);
            DataSetds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(ds);
            string spvalue = (ds.Tables[0].Rows[0][0]).ToString();
            if(spvalue == "0")
            {
                UserStatus = "Available";
            }
            elseif (spvalue == "1")
            {
                UserStatus = "Taken";
            }
            Return UserStatus;
        }

Checking username availability with ajax using jQuery,Ajax Username Check - Using jQuery,jQuery Username Availability check, Check if username exists in database with AJAX, Check Email Already Exists with Jquery Ajax, Making AJAX Calls using jQuery