$(\'#<%=nameLabel.ClientID%>\')
is being used in my script for jquery.
When this is in ... block in tha page , it works fine ,as its a content page i
There are two reasons that this doesn't work in a .js file.
Javascript files are not run through the ASP.NET engine, so the server tag <%=...%> is never executed. (If you have full control over the IIS you can register the files to be run by the engine, but it still won't work because of the second reason.)
The .js file is requested separately from the page, so the server control that you want to get the id for doesn't exist any more. It only exists while the request for the main page is handled.
You can put code to assign the id to a variable in the page, and use that variable in the .js file:
var nameLabel = '#<%=nameLabel.ClientID%>';
Like the others have explained <%=nameLabel.ClientID%>
needs to run on the server. You could however do something like this:
$("[id$=_nameLabel]")
Checks all ids and matches those that end with _nameLabel.
Simple answer : You can't use inline asp.net scripting in external .js files.
But there are two articles and source code which make this possible :
Simply click here and click here.
And also Asp.NET 4.0 brings a nice solution to this problem which is called ClientIDMode
Markup: <asp:TextBox ID="txtEcho2" runat="server" ClientIDMode="Static" />
Output: <input id="Text1" name="ctl00$MasterPageBody$ctl00$txtEcho2" />
Markup: <asp:TextBox ID="TextBox1" ClientID="Echo" runat="server" ClientIDMode="Static" />
Output: <input id="Text2" name="Echo" />
Markup: <asp :TextBox ID ="txtEcho" runat ="server" ClientIDMode ="Legacy" />
Output: <input id="ctl00_MasterPageBody_ctl00_txtEcho" name="ctl00$MasterPageBody$ctl00$txtEcho" />
For more information, drop by here
Server code does not work in external js files.
External javascript files are not served by the ASP.NET engine, so any server side tags such as <%= ... %>
will not work. You could apply a css class to the element and use a CSS selector:
$('.nameLabel')