Thursday, August 2, 2012

Get ClientID using jQuery


When using jQuery script with Asp.net controls in, we need to get the exact reference to the controls to work with the control in jQuery.

Asp.net at times changes the ClientID of the control at runtime; hence we will not be able to work with the control in jQuery, in these cases we can make use of the ClientID of the control to refer to the control as follows.

var strName = $("#<%=txtName.ClientID %>").val();
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

Example

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Asp.Net ClientID</title>
    <link type="text/css" href="Stylesheet.css" rel="Stylesheet" />
    <script type="text/javascript" src="JavaScript/jquery-1.7.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            alert('ClientID of txtName: ' + $("#<%=txtName.ClientID %>").attr('id'));
        });
      </script>         
</head>
<body>
    <form id="frmClientID" runat="server">
        Enter Name:  
        <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    </form>
</body>
</html>

Search Flipkart Products:
Flipkart.com

No comments: