When creating a control in webforms we specify a server-side id.
Below I've declared a textbox and I've given it a server-side id of m_PoNoNumberTextBox. In my server-side code I would get a reference to this textbox using that id.
<asp:TextBox runat="server" type="Text" id="m_PoNoNumberTextBox" placeholder="PO number"></asp:TextBox>
The html rendered to the browser looks like this:
<input name="ctl00$BodyContent$m_PoNoNumberTextBox" type="text" id="ctl00_BodyContent_m_PoNoNumberTextBox">
You can see webforms has created a client-side id of ctl00$BodyContent$m_PoNoNumberTextBox. So you might think it's OK to use that id in your javascript/jquery:
$(document).ready(function () {// wait for doc to load
// get a reference to the textbox using the client-side id generated by webforms
var poTextBox = $('#ctl00$BodyContent$m_PoNoNumberTextBox');
// alert user with id attribute, just to prove we have a reference
alert(poTextBox.attr('id'));
});
This is wrong. The problem is there is no guarantee that webforms will continue to generate the same client-side id. In other words it could change and your hard-coded javascript references will become incorrect.
The solution is to use the ClientID property on the textbox. This property gives us with the client-side id that will be rendered at runtime. We can write this value directly out to our javascript:
$(document).ready(function () {// wait for doc to load
// get a reference to the textbox, this time use the server-side ClientID property to write the client-side id out to javascript
var poTextBox = $('#<%= m_PoNoNumberTextBox.ClientID%>');// note that<%= %>', this writes the server side value to the javascript before the html is sent to the browser
// alert user with id attribute, just to prove we have a reference
alert(poTextBox.attr('id'));
});
#Webforms