Thursday, August 2, 2012

Reference controls using ClientID in 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.

$("#<%=chkStatus.ClientID %>")

We will have to use the same format to access the properties of the controls

$("#<%=chkStatus.ClientID %>").is(':checked')

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() {
            $("#<%=chkStatus.ClientID %>").click(function(event) {
            var labelTest = '';
if ($("#<%=chkStatus.ClientID %>").is(':checked') == true) {
              labelTest = 'Active';
            }
            else {
               labelTest = 'InActive';
            }
            //
            document.getElementById("lblStatus").innerText = labelTest;
            });
        });
      </script>         
</head>
<body>
    <form id="frmClientID" runat="server">
    <div>
        Status:   <asp:CheckBox
ID="chkStatus"
runat="server"
Text="Active" /> <br /> <br />
        <span id="lblStatus"
class="Label"></span>
    </div>
    </form>
</body>
</html>

Search Flipkart Products:
Flipkart.com

No comments: