Saturday, September 24, 2011

ID Selector examples in JQuery

In this post we will understand more about ID Selector in JQuery.  That is selecting a particular element based on his unique ID.

Continue with our earlier example of JQuery Selector

I have following data input screen


Syntax

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#ElementID").css("stylename", "stylevalue");
    });
</script>



Example 1: Lets give border color to blue to location textbox control on our asp.net web form.
Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#<%=txtLocation.ClientID%>").css("border-color", "blue");
    });
</script>

Whenever we are selecting asp.net control, it renders html id as something like
MainContent_ContentPane_txtLocation

JQuery needs unique client id, in order to apply css effect.

Since my asp.net webform is using Master page + Nested master page + Control ID
So here: MainContent_ContentPane_txtLocation
MainContent is MasterPage ID
ContentPane is Nexted MasterPage ID
txtLocation is Control ID


Please note:  I have used #<%=txtLocation.ClientID%>
# - Is to tell we are applying css based on ID.
<%=txtLocation.ClientID%> - is used to get client id of txtLocation control.


Note: If you try something like
       $("#txtLocation").css("border-color", "blue");
It won't apply any border to txtLocation, because JQuery will not be able to find txtLocation to apply CSS.


It will result in following output on browser screen.

Example 2: Lets apply yellow background color to table containing all input controls.
My table is not asp.net server control, i.e. it doesn't have runat="server"
Its html looks like <table id="tblInputForm">

Remember if control you are trying to select is not asp.net server control (i.e. not having runat="server"), then you will be able to select it directly.

Please add below script at the end of the page.

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
       $("#<%=txtLocation.ClientID%>").css("border-color", "blue");
       $("#tblInputForm").css("background-color", "yellow");
    });
</script>

It will result in following output on browser screen.

No comments:

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape