Detect IE browser | jQuery

In previous post we saw how to get IE browser in JavaScript
In this post we wiil see how to detect IE browser using jQuery. jQuery have Browser object like Navigator object in JavaScript. And using Browser object we can get Browser name, version..etc.
jQuery to get IE browser
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
      <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <title></title>
</head>
<script type="text/javascript">
    function getBrowser() {
    
        if ($.browser.msie) {
            alert('Detected IE browser');
        }
    }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="getBrowser();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

Output This will show alert message Detected IE browser.

Detect IE browser | Javascript

While working with Web projects those required cross browser compatibility we often need to detect the browser type,like ie, Firefox Mozilla, or chrome...etc.

In this post we will see how to find ie browser. This is done using navigator object in JavaScript. Navigator has appName property that we can use to find ie browser.

JavaScript to detect ie

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<script type="text/javascript">
    function getBrowserName()
    {
        if(navigator.appName=="Microsoft Internet Explorer") {
            alert("This is " + navigator.appName + " Browser");
        }
  }
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <input type="button" onclick="return getBrowserName();" value="Get Browser Name"/>
    </div>
    </form>
</body>
</html>

//Above code will show alert message "This is Microsoft Internet Explorer Browser"

Here we will see how to detect IE browser using jQuery

jQuery check uncheck all checkboxes in gridview

In this post we will see how to check and uncheck checkboxes in the gridview. We will check and uncheck checkboxes at client side in gridview using jquery. First we will add check boxes to gridview like:

Gridview with checkboxes

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
      CellPadding="3" BorderStyle="None" Font-Names="Arial">
      <FooterStyle></FooterStyle>
      <PagerStyle HorizontalAlign="Left"></PagerStyle>
      <HeaderStyle Font-Bold="True"></HeaderStyle>
      <Columns>
        <asp:TemplateField HeaderText="Select">
          <HeaderTemplate>
            <asp:CheckBox ID="checkAll" runat="server" Text="" onclick="javascript:CheckUnCheckAll(this);" />
          </HeaderTemplate>
          <ItemTemplate>
            <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" />
          </ItemTemplate>
        </asp:TemplateField>
        <asp:BoundField HeaderText="Item No." DataField="ItemNo">
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
        <asp:BoundField HeaderText="Item Name" DataField="ItemName">
          <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
        </asp:BoundField>
      </Columns>
    </asp:GridView>

Here in above code we have gridview with one checkbox in header and checkboxes for all the rows. Now we have to check all the checkboxes in gridview rows when header checkbox is checked and when header checkbox is unchecked all checkbox get unchecked. Now we have to access gridview object in jquery.

$('#<%=GridView1.ClientID %>')

In order to get and perform check-uncheck operation on checkboxes we have to call Javascript function from header checkbox of the gridview and in that function we will find all row checkboxes like:

 $('#<%=GridView1.ClientID %>').find("input:checkbox")

Now by iterating through each checkbox item we can assign header checkbox's checked status to all other checkboxes.

Iterate through gridview checkboxes to check uncheck checkboxes

<script type="text/javascript">
  function CheckUnCheckAll(chk) {
     $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
          if (this != chk) {
              this.checked = chk.checked;
            }
           });
      }
 </script>

Example to check-uncheck all checkboxes in gridview

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
      <title>Check all checkboxes in gridview using jQuery</title>
    <script type="text/javascript">
        function CheckUnCheckAll(chk) {
            $('#<%=GridView1.ClientID %>').find("input:checkbox").each(function () {
                if (this != chk) {
                    this.checked = chk.checked;
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" BorderWidth="1px"
            CellPadding="3" BorderStyle="None" Font-Names="Arial">
            <FooterStyle></FooterStyle>
            <PagerStyle HorizontalAlign="Left"></PagerStyle>
            <HeaderStyle Font-Bold="True"></HeaderStyle>
            <Columns>
                <asp:TemplateField HeaderText="Select">
                    <HeaderTemplate>
                        <asp:CheckBox ID="checkAll" runat="server" Text="" onclick="javascript:CheckUnCheckAll(this);" />
                    </HeaderTemplate>
                    <ItemTemplate>
                        <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" />
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:BoundField HeaderText="Item No." DataField="ItemNo">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField HeaderText="Item Name" DataField="ItemName">
                    <ItemStyle HorizontalAlign="Center" VerticalAlign="Middle"></ItemStyle>
                </asp:BoundField>
            </Columns>
        </asp:GridView>
        <input type="button" id="submit" value="Submit" />
    </div>
    </form>
</body>
</html>

jQuery call page codebehind method

In asp.net application sometimes we need to call codebehind method from client script. In this post we will see how to call codebehind page method using jquery ajax.

To call codebehind page method from jquery we need to make method static. Also we need to add [WebMethod] attribute for method. So the code behind method will look like:

 [WebMethod]
  public static string GetMessage()
  {
   return "Codebehind method call...";
  }

We also need to add namespace using System.Web.Services; to add [WebMethod] attribute to code behind method.
Now we can call this codebehind method using jquery ajax like

var loc = window.location.href;
$.ajax({
         type: 'POST',
          url: loc + "/GetMessage",
          data: "{}",
          contentType: "application/json; charset=utf-8"
        
        })
        .success(function (response) {
          alert(response.d);

        })
        .error(function (response) {
          alert(response.d);
        });

Here using window.location.href we are getting url of aspx page and by appending method name to it we can call code behind method.

Below code demonstrats how to call codebehind method using jquery ajax and json

jQuery ajax call codebehind page method

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
var loc = window.location.href;
$("#btnClick").click(function (event) {
$.ajax({
type: 'POST',
url: loc + "/GetMessage",
data: "{}",
contentType: "application/json; charset=utf-8"
})
.success(function (response) {
alert(response.d);
})
.error(function (response) {
alert(response.d);
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btnClick" runat="server" Text="Button" />
</div>
</form>
</body>
</html>

Below is the code behind method that will get called by jquery ajax call:

using System;
using System.Web.Services;

namespace aspnetcontrol
{
  public partial class jquerycallpagemethod : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    public static string GetMessage()
    {
      return "Codebehind method call...";
    }
  }
}

Remove Hide blogger|blogspot header navbar

Blogger or Blogspot is the easy way to write blogs. In blogger by default it shows header navbar on top. To hide blogspot|blogger navbar from header follow the below steps:
1. Login to blogger account.
2. Go to Template in new blogger view
3. Then click on Edit Html.

hide remove blogspot header navbar using css

4. Search for <b:skin>
5. Below that add css:
#navbar-iframe
{
height:0px;
visibility:hidden;
display:none;
}
This will hide or disable the blogger default header navbar.

jQuery ajax handle exception thrown by wcf

When we work with jQuery Ajax call to WCF, it may possible that WCF service will thow an exception. And we need to catch that exception in jquery ajax error routine. In order to show or get exception thrown by service we need to configure includeExceptionDetailInFaults="True" for in behavior like:

<serviceBehaviors>
  <behavior name="">
    <serviceMetadata httpGetEnabled="true" />
    <serviceDebug includeExceptionDetailInFaults="true" />
  </behavior>
</serviceBehaviors>

Now when jquery ajax call revices error then exception comes in resposeText as Message.But we need extract Message from responseText as responseText comes as cominations of error details. This can be done using jQuery.parseJSON like:



 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
        });

Now to get Message part we can use r.Message. This will give you the message that is sent by exception in wcf service.


 .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
        });

Code for jQuery ajax handle exception thrown by wcf

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response, q, t) {
          var r = jQuery.parseJSON(response.responseText);
          alert("Message: " + r.Message);
          alert("StackTrace: " + r.StackTrace);
          alert("ExceptionType: " + r.ExceptionType);
          alert("ERROR" + response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

Note: To test example of catch exception in jquery ajax thrown by wcf service, just throw an application exception or Exception with some message like:

    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      //return "WCF" + message;
      throw  new  ApplicationException("This is exception");
    }

Configure wcf service to call in jquery ajax json

In previous post we saw how to create wcf service to be get called by jquery ajax and json. After creating wcf service we need to configure wcf service in web.config in order to make it accessible.

wcf service configuration for jquery ajax call

Configure wcf service

  <system.serviceModel>
    <behaviors>
      <endpointBehaviors>
        <behavior name="GetJson">
          <enableWebScript />
        </behavior>
        <behavior name="PostJson">
          <webHttp />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
    <services>
      <service name="aspnetcontrol.Service1">
        <endpoint address="get-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="GetJson"
                  contract="aspnetcontrol.Service1" />
    
        <endpoint address="post-json"
                  binding="webHttpBinding"
                  behaviorConfiguration="PostJson"
                  contract="aspnetcontrol.Service1" />
      </service>
    </services>
  </system.serviceModel>

Create wcf service to call by jquery ajax json

In this post we will see how to create wcf service in C# that we can call through jquery ajax and json. The namespaces we need in wcf service are System.ServiceModel, System.ServiceModel.Web and System.ServiceModel.Activation.

create wcf service to be called by jquery ajax json

Example- WCF service to call by jquery ajax json

using System.ServiceModel;
using System.ServiceModel.Web;
using System.ServiceModel.Activation;
using System.Web;

namespace aspnetcontrol
{
  [ServiceContract(Namespace = "")]
  [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
  public class Service1 
  {
    [WebGet()]
    [OperationContract]
    public string GetMessage(string message)
    {
      return "WCF" + message;
    }
  }
}

Note: In above code important attributes are [ServiceContract(Namespace = "")], [OperationContract] and [WebGet()]. ServiceContract specifies that class defines service contract in application.
OperationContract specifies that a method defines and operation that is part of web service contract.
WebGet indicates service operation is logically a retrieval operation. In this way we can create wcf service to be called using jquery ajax json. In order to make service accessible we need to configure wcf service in web.config.

jQuery Ajax call to WCF service

In jQuery we can perform an asynchronous HTTP (Ajax) request. In this post we will see simple example of how jquery Ajax call to WCF service works. We can call wcf service using jquery ajax and json.

use jquery ajax to call wcf service
We can use $.ajax to call the wcf service like:
 var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });


Here in above code snippet we have set various parameters for jquery ajax call like: type: 'GET' - means request is of type GET and not POST
url: '', here we have mentioned the url of wcf service, where Service1.svc is wcf service name, get-json is address set in the web.config wcf service and GetMessage is actual method in wcf service.
data: dto is the parameter data that we need to pass to wcf service method.

Example jquery ajax call to wcf service

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>Jquery ajax json call to wcf service</title>
  <script type="text/javascript">
   $(document).ready(function () {
      $("#btnClick").click(function () {
        var dto = { message: $("#messageinput").val() };
        $.ajax({
          type: 'GET',
          url: '<%= ResolveUrl("~/Service1.svc/get-json/GetMessage") %>',
          data: dto,
          contentType: "application/json; charset=utf-8"
        })
        .success(function (response) {
          alert(response.d);
        })
        .error(function (response) {
          alert("ERROR"+response.d);
        });
      });
    });
  </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <input type="text" id="messageinput" />
    <asp:Button ID="btnClick" runat="server" Text="Button" />
  </div>
  </form>
</body>
</html>

In above example we can type some message in textbox and pass message to wcf service using jquery ajax call and get it in respose back.

Note: To run above example we need to create wcf service and configure wcf service endpoint in web.config file properly

jquery set dropdownlist exact text

We have seen how to set selected option in dropdown list by text here set dropdownlist selected option by text. In that example we used :contains selector that will look for the text and the set text in dropdownlist as selected.

dropdownlist set exact selected text
But if dropdownlist have items with same texts instance then :contains selector will get all the items with matched text. This might show last matched item selected in dropdownlist. In this case we need to use alternate way to get exact text in dropdownlist and then set it selected.

Example to set selected option in dropdown by exact text [jquery]


<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <title>set dropdown value</title>
  <script type="text/javascript">
    $(document).ready(function () {
      $("#go").click(function () {
        var inputText = $("#inputText").val();
        $("#numbers").each(function () {
          $('option', this).each(function () {
            if ($.trim($(this).text().toLowerCase()) == $.trim(inputText.toLowerCase())) {
              $(this).attr('selected', 'selected');
            };
          });
         });
       });
    });
 </script>
</head>
<body>
  <form id="form1" runat="server">
  <div>
    <label>Enter value from dropdown</label>
    <input type="text" id="inputText" />
    <asp:DropDownList ID="numbers" runat="server">
      <asp:ListItem Text="This is one" Value="1"></asp:ListItem>
      <asp:ListItem Text="This is one?" Value="2"></asp:ListItem>
      <asp:ListItem Text="This is three" Value="3"></asp:ListItem>
    </asp:DropDownList>
  </div>
  <input type="button" id="go" value="Go" />
  </form>
</body>
</html>

Summary: So by using :contains it might not work for multiple items with istance of same text. But we can iterate through dropdown items and then by matching exact text we can set dropdown list text selected.