problem with masterpage and jquery
I have a MasterPage that inside its content section I added a FORM element. When accessing that page, all my controls are renamed since the FORM is开发者_开发百科 runat=server. And thus when selecting in jquery, even the form has been renamed
How can I fix that?
thanks
With a master page, all elements will have ct100__etc appended to the ID of the element. This is a feature since its a naming container. Typically, the way to work around it is to use syntax like:
$("#<%= button.ClientID %>").click(..);
To access the longer ID's, or rely on CSS classes to identify elements. Another trick is to wrap certain sections of the form with a DIV HTML element and give it an ID to target.
HTH.
You can't, that's the behavior of .Net. What you can do is adjust your jquery usage to incorporate the ClientID of the controls you're using. The easiest way is to have some sort of translation variable injected into script in the head somewhere.
<script language="javascript">
var myControl1 = '<%=myControl1.ClientID %>';
</script>
Then you can use myControl1 as a string variable to inject the client id into your jquery calls in a more readable fashion.
Have a look at this post here
http://john-sheehan.com/blog/custom-jquery-selector-for-aspnet-webforms/
Explains it all pretty clearly. the trick is to use ClientId
In addition to the .ClientID
approach suggested in many of the other answers, you can use jQuery's endswith selector.
eg: Select the element whose id endswith "myid" (eg ctl001_form1_myid)
$('[id$="myid"]');
or if you are using .net 4, you can set ClientIdMode="false"
to prevent the renaming.
You can use Control.ClientID
for this. Something like
$("#<%= yourelement.ClientID %>")
You can also create a CSSCLASS and then access by $('.classname')
<asp:TextBox id="tb4" Text="Hello World!" cssclass="txtboxtb4" runat="server" />
alert($('.txtboxtb4').val());
Another way is put controls in span tag.
<span id="txt">
<asp:TextBox ID="txt" runat="server"></asp:TextBox>
</span>
Than you can select you element like this in jQuery.
$('#txt > input').val('Hello world');
But my way is, select element with ends with selector.
$('input[id$="txt"]').val('Hello world');
Works for my cases. Hope help.
精彩评论