jQuery, ASP.NET Client ID and External JS File
$('<%= txtName.ClientID %>').focus( //Blah Blah);
If you are writing this above code directly in your .aspx page, then your jQuery code will work but if you move the same code to an external or separate js (Java Script) file, you will get an error "Uncaught Error: Syntax error, unrecognized expression".
Related Post:
- Using jQuery with ASP.NET
- Fix for ASP.NET Checkbox -jQuery click event getting fired twice issue
- Turn off autocomplete for ASP.NET textbox using jQuery
Any idea why this works on .aspx page?
Well the reason is, when the jQuery code is placed in .aspx page the jQuery code line such as <%=txtName.ClientID%>, is processed on the server and it is replaced with a proper ID generated by ASP.NET for the control. And when it is placed into a seperate JS file, ASP.NET has no role to play. Since the js file is not processed by ASP.NET and Client ID is not replaced, jQuery will throw the error "Uncaught Error: Syntax error, unrecognized expression" for characters < and > .
So how to fix this?
To fix this error, all you need to do is to remove < and > characters from your jQuery code. Which means you need to change your selectors and there are couples of ways to do this. For example the jQuery code,
$('<%= txtName.ClientID %>').focus( //Blah Blah);
can be replaced with,
$("input[id*='txtName']").focus( //Blah Blah);
The above code will select input controls which have "txtName" anywhere within the element's ID attribute value. You can also select the elements via class selectors.
If you are using ASP.NET 4.0, then you can take advantage of ClientIDMode property which when set to Static will keep the same ID in rendered page. For example:
<asp:TextBox ID="txtName" runat="server" ClientIDMode="static" />
will generate something like:
<input type="text" id="txtName" />
So your ID will not change and you don't have to use ClientID property to access the control in jQuery.
Feel free to contact me for any help related to jQuery, I will gladly help you.