.net javascript master pages garbling element name is there a way around it? [duplicate]
Possible Duplicate:
Any way to prevent master pages from changing element IDs?
Hi
I have a .net 2.0 web page that is using a master page. On the page in question is a form and I am trying to call one of the sub element. The form element name is:
"contact_label" - its an asp:Label
But when I look at the source I am getting that the name is:
"ctl00_ContentPlaceHolder1_contact_label"
Is there a way to get around this 'name garbling?'
I have read that I should be able to reference it something like this:
document.getElementById("<%= contact_label.ClientID %>")
but that didn't work for me either...
开发者_C百科This is all .net 2.0 with javascript.
Thanks, R.
If you want to use javascript you could make some global variables for your javascript to use that get setup before you execute any of your other javascript calls. I prefer this method as it reduces the amount of inline code you need all over the place to get control IDs and it centralizes it all in one location.
So at the beginning of your script code do:
// In your javascript
var myTextBoxId = "<%= myTextBox.ClientID %>";
var myButtonId = "<%= myButton.ClientID %>";
Then in your javascript code whenever you need to use it you can just do:
var myTextBox = document.getElementById(myTextBoxId);
var myButton = document.getElementById(myButtonId);
Using Jquery will make this even cleaner looking. For example to get a textbox value:
var myTextBoxValue = $("#" + myTextBoxId).val();
// or if you dont want to use the initializers to store the ids
var myTextBoxValue = $("#" + "<%= myTextBox.ClientID %>").val();
You can use jQuery and its "attribute ends with" capabilities on the id, such as:
var item = $("span[id$=contact_label]");
var text = item.text();
The line of code suggested to you
document.getElementById("<%= contact_label.ClientID %>")
should do what your asking.
When you look at the page source what do you see in place of the "<%= contact_label.ClientID %>"
Is the javascript code in the webform or the MasterPage?
Also try single quotes instead of double quotes in the javascript
document.getElementById('<%= contact_label.ClientID %>')
the id of elements need to be unique if you use runat="server", and document.getElementById("<%= contact_label.ClientID %>");
must get elementbyId.
精彩评论